rhy*_*lay 4 firebase angularfire2 angular google-cloud-firestore
我正在按照Firestore的说明存储阵列:https: //firebase.google.com/docs/firestore/solutions/arrays
现在我想做的就是推到这张地图。例如现在我有:
Contacts
contact1: true
Run Code Online (Sandbox Code Playgroud)
但是我想添加或删除一个联系人,例如:
Contacts
contact1: true
contact2: true
Run Code Online (Sandbox Code Playgroud)
我尝试获取Contacts映射并使用push方法,但是由于它不是传统数组,因此我认为这不会起作用。例如:
this.afs
.doc(`groups/${group.id}`)
.ref.get()
.then(doc => {
let contacts: Array<any> = doc.data().contacts;
contacts.push({ // error here as push is not a function
[contactId]: true
});
console.log(contacts);
});
Run Code Online (Sandbox Code Playgroud)
有没有更简单的方法可以执行此操作-我错过了什么吗?
只需推入地图
使用update()如下
const db = firebase.firestore();
const collection = db.collection('collectionId');
collection.doc(`groups/${group.id}`).update({
"Contacts.contact3":true
}).then(function(){
console.log("Successfully updated!");
});
Run Code Online (Sandbox Code Playgroud)
首先,由于映射不是数组,因此不能在对象上使用push方法。
您可以简单地使用.或[]运算符在JS中访问/添加/更新地图的值。
对于存储在Firestore中的对象(例如Arrays和Objects),您不能真正直接将值“推”到它们。您首先需要获取包含它们的文档,然后在本地更新它们的值。
完成后,将值更新为Firestore。
为了简化流程,runTransaction()如果您使用的是Cloud Functions ,则可以使用Firestore SDK或Admin SDK提供的方法。
这是将为您完成工作的代码。
const docRef = this.afs.doc(`groups/${groupId}`);
db.runTransaction((t) => { // db is the firestore instance
return t.get(docRef).then((doc) => { // getting the document from Firestore
// {} is a fallback for the case if the "obj" is not present in the firestore
const obj = doc.get("contacts") ? doc.get("contacts") : {};
obj[contactId] = true; // updating the value here locally
t.set(docRef, { contacts: obj }, { // updating the value to Firestore.
merge: true,
});
return;
}).then((result) => {
console.log('map updated', result);
return;
}).catch((error) => handleError(error));
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4382 次 |
| 最近记录: |