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

时间:2017-03-07 03:22:32

标签: javascript node.js mongodb mongodb-query

这是我的食谱对象

{ 
  _id: "A uuid",
  title: "Recipe title",
  comments: [
    {
      _id: 1,
      poster: "poster name",
      comment: "the comment"
    },
    {
      _id: 2,
      poster: "poster1 name",
      comment: "the comment1"
    }
   ]
 }

我想用以下对象更新我的id为2的注释字段,比如对象1

{
  "poster": "xd",
  "comment": "best recipe ever" 
}

不知道上述对象中存在多少个字段。它可能有也可能没有海报价值或评论价值。 功能 -

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

1 个答案:

答案 0 :(得分:1)

您的查询应该像使用。$将在嵌入式文档中为您更新特定结果。

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