[英]Not able to add a new field to an existing document in firestore
我正在尝试使用updateDoc
方法向现有文档添加一个新字段(反应),但它没有添加一个新字段。 这就是我正在做的事情:
const newUserReactions = [...reactions, newReaction]
console.log(newUserReactions)
updateDocument(docID, { reactions: newUserReactions })
文档中不存在reactions
字段
更新文档:
const updateDocument = async (id, updates) => {
dispatch({ type: "IS_PENDING" })
try {
const updatedDocument = await updateDoc(doc(db, c, id), updates)
dispatchIfNotCancelled({ type: "UPDATED_DOCUMENT", payload: updatedDocument })
return updatedDocument
} catch (error) {
dispatchIfNotCancelled({ type: "ERROR", payload: error })
return null
}
}
将数据写入 Cloud Firestore 有多种方法:
在集合中设置文档的数据,明确指定文档标识符。
将新文档添加到集合中。 在这种情况下,Cloud Firestore 会自动生成文档标识符。
使用自动生成的标识符创建一个空文档,然后将数据分配给它。
当您尝试更新 Cloud Firestore 中的文档时,需要知道其 ID。 要更新文档的某些字段而不覆盖整个文档,请使用update()
方法:
您可以按照以下算法逻辑进行更新。
1.根据您的条件运行查询以确定文档 ID。
2.使用单个更新或一个或多个批量写入来更新文档[1]
const docRef = db.collection('objects').doc('some-id');
// Update the timestamp field with the value from the server
const res = await docRef.update({
timestamp: FieldValue.serverTimestamp()
});
请注意,您只需要步骤 1 中的文档 ID。因此您可以运行仅返回 ID 的查询。 这在客户端 SDK 中是不可能的,但可以通过 REST API 和 Admin SDK 来完成,如此处所示 [2]
[1] https://firebase.google.com/docs/firestore/manage-data/add-data#server_timestamp
[2] : 如何获取 Cloud Firestore 集合中的文档 ID 列表?
除了指定的错误之外,是否还有任何特定错误? 另外,请分享来自 Firebase 控制台的 Firestore 数据的前后屏幕截图。
您可以参考以下链接以供进一步参考:
[3]: https ://firebase.google.com/docs/firestore/manage-data/add-data#add_a_document
[4]: https ://firebase.google.com/docs/firestore/manage-data/add-data#set_a_document
[5]: https ://cloud.google.com/firestore/docs/samples/firestore-data-set-field#firestore_data_set_field-nodejs [6]: 如果我知道它的标题字段值,我可以向现有文档添加新字段吗而不是身份证?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.