How to update the array of object


#1

I tried in different ways to update the array of object in mongodb

article:Array
0:Object
articleId:1537597357491
status:“pending”

this is my mongo database structure, I wrote in my nodejs is:
userRouter.post(’/updateMultipleArticles’, function (req, res) {
// console.log(req.body.articleid);
console.log(req.body.status);
console.log(req.body._id);
console.log(req.body.articleid);

  Collections.user.update(
    { 
      _id : req.body._id, 
      article: articleId = req.body.articleid
      },

    { 
      $set : { "article.0.status" : req.body.status } 
    },
    function (req, res){ 
            {}
        },
        
        function (error, resp) {
        if (error)
        return console.log("Error: " + error.message);
       return res.status(200).send(resp);
    })
});

I get the updated status value in console, but the value is not updating in mongodb. can any one please helpme


#2

Check the MongoDB update operators for arrays

https://docs.mongodb.com/manual/reference/operator/update-array/


#3

you could also update the hole Array.
Extract, manipulate and insert.

For some use cases we have to do it.


#4

In mongodb array i have few more values are there like title, keywords, description. For easy way of understanding i drop to you only status. I need to update only status in array. I cant find my error, where it occurs. and i gone through this link https://docs.mongodb.com/manual/reference/operator/update-array/
but i am not found my error can you please tell me, what i wrote the syntax is correct or not, if not what is my error


#5

Check this page. It’s explained a little better:

https://docs.mongodb.com/manual/reference/operator/update/positional/#update-values-in-an-array


#6

Thanks for your reply. I wrote my back-end based on this reference
https://docs.mongodb.com/manual/reference/operator/update/positional/#update-values-in-an-array
But i got an error.