我有下面的代码,第一次运行时会创建一个新集合,其文档 ID 等于我的 UID。这个新创建的文档有一个名为“array”的数组,其中包含cocktailInformation对象。到目前为止一切正常。
const saveData = (uid) => {
db
.collection('users')
.doc(uid)
.set({
array: [ cocktailInformation ]
})
.then(function() {
console.log('Document successfully written!');
})
.catch(function(error) {
console.error('Error writing document: ', error);
});
};
当我想向本文档中的数组添加更多对象时,就会出现问题。我检查了 firestore 文档以了解如何执行此操作,它显示了以下内容
var washingtonRef = db.collection("cities").doc("DC");
// Atomically add a new region to the "regions" array field.
washingtonRef.update({
regions: firebase.firestore.FieldValue.arrayUnion("greater_virginia")
});
// Atomically remove a region from the "regions" array field.
washingtonRef.update({
regions: firebase.firestore.FieldValue.arrayRemove("east_coast")
});
但我不知道如何集成它,因为当前代码仅使用我发送到 firestore 的对象更新当前对象。谁能给我一些建议吗?顺便说一句,这是一个 react 应用程序
最佳答案
您可以通过执行以下操作来更新文档:
db.collection('users').doc(uid).update({
array: firebase.firestore.FieldValue.arrayUnion("value")
});
关于javascript - 如何将对象添加到firestore中的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61459203/