Reputation: 37
this is my recipe object
{
_id: "A uuid",
title: "Recipe title",
comments: [
{
_id: 1,
poster: "poster name",
comment: "the comment"
},
{
_id: 2,
poster: "poster1 name",
comment: "the comment1"
}
]
}
I want to update my comment field whose id is 2 with the following object, say object 1
{
"poster": "xd",
"comment": "best recipe ever"
}
It is not known how many fields are present in the above object. It may or may not have poster value or comment value. function-
updateCommentOfRecipe(updatedComment,commentId,recipeId) {
return recipes().then((recipeCollection) => {
let updatedCommentData = {};
updatedCommentData._id=commentId;
if (updatedComment.poster) {
updatedCommentData.poster = updatedComment.poster;
}
if (updatedComment.comment) {
updatedCommentData.comment = updatedComment.comment;
}
return recipeCollection
.update( {_id:recipeId, comments:{_id:commentId} }
,{$set :{comments:updatedCommentData}}).then((result) =>{
let j=this.getRecipeById(recipeId).comments;
for (let i=0;i<j.length;i++) {
if (j[i]._id==commentId)
return j[i];
}
});
});
},
Upvotes: 0
Views: 61
Reputation: 1525
your query should be like use of .$ will update the specific result for you in embedded document.
.update( {_id:recipeId, "comments._id":commentI }
,{$set :{"comments.$.comment:updatedCommentData}}).then((result) =>{
let j=this.getRecipeById(recipeId).comments;
for (let i=0;i<j.length;i++) {
if (j[i]._id==commentId)
return j[i];
}
});
Upvotes: 1