我正在尝试推送一个数组元素,但正在销毁那里的所有内容并替换为推送的数据:
db .collection('households')
.doc(householdId)
.set( { users: [uid], }, { merge: true }, )
.then(() => { resolve(); })
.catch(() => reject());
我认为合并真的不会破坏已经存在的数据吗?与firestore api docs有点挣扎。
这是我的数据结构:
households
2435djgnfk
users [
0: user1
1: user2
]
谢谢!
最佳答案
您应该使用 Firestore Transaction为了这。
const householdRef = db.collection('households').doc(householdId);
const newUid = '1234'; // whatever the uid is...
return db.runTransaction((t) => {
return t.get(householdRef).then((doc) => {
// doc doesn't exist; can't update
if (!doc.exists) return;
// update the users array after getting it from Firestore.
const newUserArray = doc.get('users').push(newUid);
t.set(householdRef, { users: newUserArray }, { merge: true });
});
}).catch(console.log);
更新数组或存储对象而不首先获取它总是会破坏 firestore 中该数组/对象内的旧值。
这是因为它们是字段,而不是实际的文档本身。因此,您必须先获取文档,然后再更新值。
关于javascript - 如何在 Firebase Firestore 中推送数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49915854/