如何在mongodb中嵌套模式更新?

时间:2017-11-19 19:58:25

标签: mongodb meteor

我正在研究流星。我正在尝试用通信系统制作博客。对于帖子插入我的架构是这样的:

Posts.insert({
                    post:post,
                    author:username,
                    date:date,
                    createdAt:new Date(),
                    comment:{
                        commentBy:'',
                        commentMsg:''
                    },
                    userId:Meteor.userId()
                })

首先评论部分为空白。当用户评论特定帖子然后评论部分被填写。 我正在尝试更新此架构:

Posts.update(thisPost,{$addToSet:{comment.commentedBy:Name,comment.commentMsg:post}});

但它不起作用。如何做到正确?

3 个答案:

答案 0 :(得分:1)

用于输入多个注释,该字段应为数组。

comments:[{
   Commentedby:String,
   CommentedMsh:string
}]

您可以使用$ addtoset或$ push,

db.update({_id:post._id},{$push:{comments:newComment}})

OR

db.update({_id:post._id}, { $addToSet: { comments : comment });

答案 1 :(得分:0)

我认为您需要在任何点引用周围加上引号,如下所示:

Posts.update(thisPost,{$addToSet:{"comment.commentedBy":Name,"comment.commentMsg":post}});

原因是因为如果你不这样做,你的编译器会尝试在本地进行对象引用,这不是你想要的,如果你把它作为一个字符串传递,那么Mongo将按预期进行。

答案 2 :(得分:0)

我在您提供的信息中可以找到两个问题。 首先,comment属性应该是一个数组/集合,因此您应该按照以下方式启动它(重命名为注释):

Posts.insert({
    ...
    comments:[],
    ...
})

第二,最重要的是回答你的问题,根据文档,更新的第一个参数应该是选择器,ObjectID或字符串id。 https://docs.meteor.com/api/collections.html#Mongo-Collection-update

因此,您的更新应如下所示:

var comment = { commentBy: 'user-id', commentMsg: 'le-message' }
Posts.update(post._id, { $addToSet: { comments : comment });
相关问题