I am using firebase firestore
to create my website, this is one sample of document:
As you can see, I have a field call commentList
and its type is array
, now I want to push more document in the the array and this is how I did (and it not work out, of course):
const {db} = require('../util/admin');
exports.add__comment = (req, res, next) => {
const {comment, displayName, uid} = req.body;
const {id} = req.params;
return db
.collection('instagram__posts')
.doc(id)
.set(
{
commentList: [
{comment, uid, displayName, createAt: new Date().toISOString()},
],
},
{merge: true}
)
.then((doc) => {
return res.status(200).json({message: 'comment created', doc});
})
.catch((err) => {
res.status(500).json({err});
console.log(err);
});
};
Instead of adding more document to commentList
, it replace all current documents with new data. Please help me and pardon me for my bad English. Once again thank you so much and have a good day.
Try push element to direct path.
firebase.firestore()
.collection('instagram__posts')
.doc(id)
.collection('commentList')
.add({comment, uid, displayName, createAt: new Date().toISOString()})
Show details here: https://cloud.google.com/firestore/docs/manage-data/add-data#update-data
If you want to add another element to a list type field, use update()
and FieldValue.arrayUnion()
, as shown in the documentation .
db
.collection('instagram__posts')
.doc(id)
.update({
commentList: firebase.firestore.FieldValue.arrayUnion({comment, uid, displayName, createAt: new Date().toISOString()})
})
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.