Does somebody know how to add an object to an array in Google Firestore? I've searched everywhere and tried a lot of things but nothing worked out. As you can see in the picture I'm using
const sendMessage = async (data, docID) => {
const query = await db.collection("livestreams").doc(docID);
const newDataObj = {
created_At: data.created_At,
displayName: data.displayName,
message: data.message,
ownerThumbnail: data.ownerThumbnail,
userID: data.userID
};
const addObjToArr = await query.update({
chat: firebase.firestore.FieldValue.arrayUnion(newDataObj)
});
};
But this only works for adding a basic value to the array. If I want to add an object this doesn't works and I can't find any solution online.
I'm using javascript/web.
Your code should work. Note that you don't need to do await db.collection("livestreams").doc(docID);
since doc()
is not asynchronous.
const sendMessage = async (data, docID) => {
try {
const query = db.collection("livestreams").doc(docID); //<-- remove await
const newDataObj = {
created_At: data.created_At,
displayName: data.displayName,
message: data.message,
ownerThumbnail: data.ownerThumbnail,
userID: data.userID
};
const addObjToArr = await query.update({
chat: firebase.firestore.FieldValue.arrayUnion(newDataObj)
});
} catch (error) {
console.log(error);
// return something ...
}
};
However, note four important points:
update()
method works only if the document already exists. You may use set()
with the merge option if your know your doc might not exist.arrayUnion()
method with the exact same object, no new array element is created.
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.