How to update nested array of all elements in mongodb


#1

a
I am trying to update title of all objects in Content array.
I wrote this
userRouter.post(’/updatecontent’,(req,res)=>{
console.log(req.body._id);
console.log(req.body.articleId);
console.log(req.body.title);
Collections.user.update({_id:req.body._id,article:{$elemMatch:{articleId:req.body.articleId}}},{"set":{"article.0.content..title":req.body.title}},function(err,result){
if(err)
res.send(err)
else
res.send(result)
console.log(result);
})
})
Here the data is updating but only one problem. let if i kept 0 object of title is Apple and 1 object of title is Orange and 2 object of title is Mango. then i am getting result all objects of title is Mango only.

Can someone please help. How to sort out this and what i need to put.
Thanks in advance.


#2

can you please use the code tag for readability

type or paste code here

And can you try to make some examples where the error is happening. I don’t understand what you are trying to achieve.

I don’t know if its possible, but it would be better if you would have more objects so the request would be easier.


#3
userRouter.post(’/updatecontent’,(req,res)=>{
console.log(req.body._id);
console.log(req.body.articleId);
console.log(req.body.title);
Collections.user.update({_id:req.body._id,article:{$elemMatch:{articleId:req.body.articleId}}},{"set":{"article.0.content..title":req.body.title}},function(err,result){
if(err)
res.send(err)
else
res.send(result)
console.log(result);
})
})

I wrote this in my backend for updating title in my content array.

My mongodb structure is like this
a

Here i am trying to update title of all objects in content array. when i tried to update like this

content:Array
0:Object
title:"xx"
1:Object
title:"yy"
2:Object
title:"zz"

I am getting result this

content:Array
0:Object
title:"zz"
1:Object
title:"zz"
2:Object
title:"zz"

#4

ok and what do you expect?
Can you make an example where it is not right


#5

I am expecting result this.

content:Array
0:Object
title:"xx"
1:Object
title:"yy"
2:Object
title:"zz"