简体   繁体   中英

update the specified field with only the supplied changes, mongodb

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];
                    }
                });
        });
    },     

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];
                    }
                });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM