I am working on node js app using express.js and mongodb with mongoose module to handle the database.
in one case I need to update a user property languages
using findOneAndUpdate
method. this property is an array of objects should looks like [{"language":"Ar","level":4}]
when I update it using the following nodejs code :
User.findOneAndUpdate({_id:mongoose.Types.ObjectId(req.body.id)},
{$set:{[req.body.key]:req.body[req.body.key]}},(err,doc)=>{
console.log(req.body) // {id:5d1619fa7c11fa102210ef86,"languages":[{"language":"Ar","level":4}],key:"languages"}
if (!err) {
res.json(200,doc);
}else{
res.json(500,{error:err});
}
})
I get the following results
but when I try same thing from the mongo shell
db.users.findOneAndUpdate({"_id" : ObjectId("5d1619fa7c11fa102210ef86")},{ '$set': {"languages":[{"language":"Ar","level":4}]} })
I get the correct result
which is the correct expected results.
any idea why the nodejs snippet not working properly. thanks in advance.