Skip to content
Advertisement

Push object to array in mongodb nodejs [closed]

This is my mongodb collection.

I want to push object to array with findOneAndUpdate().

This is my nodejs code.

url = req.params.posturl
         filter = { url: url }
         update = { comments: (result.like + 1) }
         // maybe you can try save/get this to/in .json
         Blog.findOneAndUpdate(filter, update)
            .then((result) => {
               res.json({ status: 1 })
            })
            .catch((error) => {
               console.log(error);
            })

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;

const url = req.params.posturl
const newComment = req.body.comment
const filter = { url }
const willBePush = { comments: newComment }
Blog.findOneAndUpdate(filter, { $push: willBePush })
  .then((result) => {
    /** Do whatever with response if you want to see new document you can pass { new: true } as option for findOneAndUpdate method*/
    console.log(result)    
  })
  .catch((error) => {
    console.log(error);
  })

References:

$push

$set

mongoose documents

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement