I'm trying to add a new field(reactions) to an existing document using updateDoc
method but it's not adding a new field. This is how I'm doing:
const newUserReactions = [...reactions, newReaction]
console.log(newUserReactions)
updateDocument(docID, { reactions: newUserReactions })
reactions
field doesn't exist on the document
updateDocument:
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
}
}
There are several ways to write data to Cloud Firestore:
Set the data of a document within a collection, explicitly specifying a document identifier.
Add a new document to a collection. In this case, Cloud Firestore automatically generates the document identifier.
Create an empty document with an automatically generated identifier, and assign data to it later.
When you are trying to update a document in Cloud Firestore requires knowing its ID. To update some fields of a document without overwriting the entire document, use the update()
method:
You can do the updates by following the below algorithmic logic.
1.Run a query with your conditions to determine the document ID.
2.Update the documents with individual updates, or with one or more batched writes[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()
});
Note that you only need the document ID from step 1. So you could run a query that only returns the IDs. This is not possible in the client-side SDKs, but can be done through the REST API and Admin SDKs as shown here [2]
[1] https://firebase.google.com/docs/firestore/manage-data/add-data#server_timestamp
[2] : How to get a list of document IDs in a collection Cloud Firestore?
Are there any specific errors other than the one specified ? Also, please share the pre and the post screen-shot of the Firestore Data from Firebase console.
You may refer the following links for further reference:
[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] : Can I add new fields to existing document if I know its title field value and not the id?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.