我在应用程序中使用 Firestore,并且有一个名为“投票”的地图字段,用于显示用户的赞成票或反对票。它看起来像这样:
我想添加一个选项来从那里删除元素,这就是我现在得到的:
//getting the user's votes dictionary and removing the post from it.
userRef.getDocument { (doc, error) in
if let _ = error { completion(false) }
guard let dict = doc?.data()?[USER_VOTES] as? [String: Any] else { return }
currentDict = dict
currentDict.removeValue(forKey: id)
}
//setting the votes dictionary with the updated one.
userRef.setData(currentDict) { (error) in
if let _ = error { completion(false) }
else { completion(true) }
}
对我来说,它看起来并不高效,因为每次用户尝试从该字典中删除元素时,我都必须写入数据库。这可能会减慢该过程,据我了解,Firestore 的免费层限制了写入次数。
有没有更好的方法,也许可以直接从用户文档中删除它?我试图寻找答案,但找不到任何对我有用的东西。
以这个为例:删除 Firebase 中的字典元素 https://stackoverflow.com/questions/38466994/removing-a-dictionary-element-in-firebase看起来像是我需要做的,但我无法让它发挥作用。
编辑:
我尝试像这样删除它
userRef.updateData([
USER_VOTES:[
id: FieldValue.delete()
]
]) { (error) in
if let _ = error { completion(false) }
}
该应用程序崩溃说:
Terminating app due to uncaught exception 'FIRInvalidArgumentException', reason: 'FieldValue.delete() can only appear at the top level of your update data
为了能够删除特定字段,您应该按照上述步骤操作here https://cloud.google.com/firestore/docs/manage-data/delete-data.
For your case I have created the following under collection 'voting':
因此,要删除 vote2 字段,您应该使用:
// Get the `FieldValue` object
let FieldValue = require('firebase-admin').firestore.FieldValue;
// Create a document reference
let fieldRef = db.collection('voting').doc('votes');
// Remove the 'vote2' field from the document 'votes'
let removeField = fieldRef.update({
vote2: FieldValue.delete()
});
And here is the document after running the above:
EDIT :
If the data model is a map inside a document, for example:
然后,以下是如何删除文档内数组内的字段:
let docRef = db.collection('voting').doc('user1');
let removeField = docRef.set({'votes':
{['id_vote_1'] : FieldValue.delete()}}, {merge: true});
这是运行上述命令后的文档:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)