这是我的食谱对象

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


我想用以下对象(例如对象1)更新ID为2的注释字段。

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

最佳答案

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

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

关于javascript - 仅使用提供的更改更新指定字段mongodb,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42639603/

10-12 13:04
查看更多