This is my mongodb collection.
I want to push object to array with findOneAndUpdate().
This is my nodejs code.
JavaScript
x
12
12
1
url = req.params.posturl
2
filter = { url: url }
3
update = { comments: (result.like + 1) }
4
// maybe you can try save/get this to/in .json
5
Blog.findOneAndUpdate(filter, update)
6
.then((result) => {
7
res.json({ status: 1 })
8
})
9
.catch((error) => {
10
console.log(error);
11
})
12
How can i do this?
Advertisement
Answer
You can use $push
operator for updating an array. Actually you have a few ways too for updating a document like $set
operator or find one and change the document then save new document this will be update your document.
TLDR code here;
JavaScript
1
13
13
1
const url = req.params.posturl
2
const newComment = req.body.comment
3
const filter = { url }
4
const willBePush = { comments: newComment }
5
Blog.findOneAndUpdate(filter, { $push: willBePush })
6
.then((result) => {
7
/** Do whatever with response if you want to see new document you can pass { new: true } as option for findOneAndUpdate method*/
8
console.log(result)
9
})
10
.catch((error) => {
11
console.log(error);
12
})
13
References: