是否可以使用以前的状态更新firestore?
例如,我有一个地址文档,其中有一个 users
字段,其中包含与该地址关联的用户数组。
每当我想向此数组添加新用户时,我都需要以前的数组,否则我最终会用新数据覆盖当前数据。
所以我最终得到了类似的结果。
firestore()
.collection("addresses")
.doc(addressId)
.get()
.then(doc => {
this.db
.collection("addresses")
.doc(addressId)
.update({
users: [...doc.data().users, id]
})
});
有没有一种方法可以访问以前的数据而无需嵌套调用?
如果没有
有没有更好的方法来管理关系?
最佳答案
如果您需要以前的值来确定新值,则应使用 transaction 。这是确保不同客户端不会意外覆盖彼此操作的唯一方法。
不幸的是,事务还需要嵌套调用,因为这是获取当前值的唯一方法,甚至还有一个额外的包装器(用于事务。
var docRef = firestore()
.collection("addresses")
.doc(addressId);
return db.runTransaction(function(transaction) {
// This code may get re-run multiple times if there are conflicts.
return transaction.get(docRef).then(function(doc) {
transaction.update(docRef, { users: [...doc.data().users, id ]});
});
}).then(function() {
console.log("Transaction successfully committed!");
}).catch(function(error) {
console.log("Transaction failed: ", error);
});
最佳解决方案是使用不需要当前值即可添加新值的数据结构。这就是原因之一Firebase recommends against using arrays :当多个用户可能向数组添加项目时,它们本质上很难扩展。如果不需要维护用户之间的顺序,我建议为用户使用类似集合的结构:
users: {
id1: true,
id2: true
}
这是一个包含两个用户(id1
和 id2
)的集合。 true
值只是标记,因为字段不能没有值。
通过这种结构,添加用户就像这样简单:
firestore()
.collection("addresses")
.doc(addressId)
.update({ "users.id3": true })
另请参阅Firestore documentation on Working with Arrays, Lists, and Sets
关于javascript - 使用之前的状态更新 firestore,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48129052/