简体   繁体   English

仅使用提供的更改更新指定字段mongodb

[英]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 我想用以下对象(例如对象1)更新其id为2的注释字段。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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