Insert Into Array of object MongoDB Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Insert Into Array of object MongoDB without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have

{
    "_id" : ObjectId("5a25af80d2c4dd065991dccc"),
    "username" : "abc@gmail.com",
    "password" : "$2a$10$ptFyLKtyyrL5gMYdXS6wV.HLUA4Py5iudMJDldf5qsHFS4.9TPCyy",
    "role" : "Admin",
    "__v" : 0,
    "list" : [ 
        {
            "name" : "We",
            "arr" : [ 
                "5a26d554677475818a795f75", 
                "5a395bb0976d5304c07f7dd4"
            ]
        }, 
        {
            "name" : "sandeep",
            "arr" : [ 
                "5a26d554677475818a795f75"
            ]
        }
    ]
}

I want to add an element inside list.arr where name = ‘we’ and add only if the element does not exist

how do i perform this query.

Answer

By using this nested query I solved this problem. I’m doing it with Node JS

router.post('/prevList', (req, res) => {
  User.update({'_id':req.user.id, list: { $elemMatch: { name: req.body.name } } },{  $addToSet: { "list.$.arr": {$each: req.body.arr} } },function(err,data) {
    console.log(data);
    res.send(data)
  });
});

Here

req.body: {name:'we',arr:["5a395bb0976d5304c07f7dd4"]}

and req.user.id is the auth id.

Hope this helps you all too.

We are here to answer your question about Insert Into Array of object MongoDB - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji