我目前正在尝试使用Firestore,但遇到了非常简单的问题:“更新数组(又称子文档)”。
我的数据库结构非常简单。例如:
proprietary: "John Doe", sharedWith: [ {who: "first@test.com", when:timestamp}, {who: "another@test.com", when:timestamp}, ], 我正在尝试(没有成功)将新记录推入shareWith对象数组。
我试过了:
// With SET firebase.firestore() .collection('proprietary') .doc(docID) .set( { sharedWith: [{ who: "third@test.com", when: new Date() }] }, { merge: true } )
// With UPDATE firebase.firestore() .collection('proprietary') .doc(docID) .update({ sharedWith: [{ who: "third@test.com", when: new Date() }] }) 没有效果。这些查询将覆盖我的数组。
答案可能很简单,但我找不到它... 问题来源于stack overflow
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
您可以使用事务(https://firebase.google.com/docs/firestore/manage-data/transactions)获取数组,将其压入数组,然后更新文档:
const booking = { some: "data" };
const userRef = this.db.collection("users").doc(userId);
this.db.runTransaction(transaction => {
// This code may get re-run multiple times if there are conflicts.
return transaction.get(userRef).then(doc => {
if (!doc.data().bookings) {
transaction.set({
bookings: [booking]
});
} else {
const bookings = doc.data().bookings;
bookings.push(booking);
transaction.update(userRef, { bookings: bookings });
}
});
}).then(function () {
console.log("Transaction successfully committed!");
}).catch(function (error) {
console.log("Transaction failed: ", error);
});