MongoDB更新与对象数组内的查询匹配的对象

时间:2017-11-19 03:09:01

标签: javascript database mongodb nosql

我想更新帖子的集合并更新每条评论。我该怎么做?

这是一个示例:

{
    "pid": "kennethlumalicay-ja55nh40ja64br0h",
    ...more_stuff,
    "comments": [
        {
            "uid": "kennethlumalicay-ja55nh40",
            "username": "kennethlumalicay",
            "usertag": "Full Stack",
            "comment": "hey"
        },
        {
            "uid": "kennethlumalicay-ja55nh40",
            "username": "kennethlumalicay",
            "usertag": "Full Stack",
            "comment": "what"
        },
        {
            "uid": "kennethlumalicay-ja55nh40",
            "username": "kennethlumalicay",
            "usertag": "Full Stack",
            "comment": "now"
        }
    ]
}, ...other_posts

这是我的代码:

  Post.updateMany({ 'comments.uid': user.uid }
    , { 'comments.$': {
      username: user.username,
      usertag: user.usertag
    }}
    , null
    , () => {
      fetchPosts(null, (posts) => {
        cb({
          posts: posts,
          user: user
        });
      });
    });

我的期望: 找到每个对uid发表评论的帖子并更新每条评论。

{
    "pid": "kennethlumalicay-ja55nh40ja64br0h",
    ...more_stuff,
    "comments": [
        {
            "uid": "kennethlumalicay-ja55nh40",
            "username": "kennethlumalicay",
            "usertag": "Front End", // updated
            "comment": "hey"
        },
        {
            "uid": "kennethlumalicay-ja55nh40",
            "username": "kennethlumalicay",
            "usertag": "Front End", // updated
            "comment": "what"
        },
        {
            "uid": "kennethlumalicay-ja55nh40",
            "username": "kennethlumalicay",
            "usertag": "Front End", // updated
            "comment": "now"
        }
    ]
}, ...other_posts

反而会发生什么: 查找每个对uid发表评论的帖子,并更新一条评论并删除其他属性。

{
    "pid": "kennethlumalicay-ja55nh40ja64br0h",
    ...more_stuff,
    "comments": [
        { // removed uid and comment
            "username": "kennethlumalicay",
            "usertag": "Front End"
        },
        { // nothing
            "uid": "kennethlumalicay-ja55nh40",
            "username": "kennethlumalicay",
            "usertag": "Full Stack",
            "comment": "what"
        },
        { // nothing
            "uid": "kennethlumalicay-ja55nh40",
            "username": "kennethlumalicay",
            "usertag": "Full Stack",
            "comment": "now"
        }
    ]
}, ...other_posts

这是否可以实现或者我应该创建另一个评论集合并只存储帖子ID? 或者我可能只是每当我要呈现评论时才会在uid上获取用户数据库?但这听起来不太好。

1 个答案:

答案 0 :(得分:0)

您在“coments。$”中使用“$”运算符。

查看文档:{​​{3}}

  

$作为占位符来更新匹配的第一个元素   更新中的查询条件。

另外,我认为您想使用$ set运算符,所以不要使用仅包含用户名 usertag 田地。

尝试:

Post.updateMany({ 'comments.uid': user.uid }
    , { 'comments': $set: {
      username: user.username,
      usertag: user.usertag
    }}
    , null
    , () => {
      fetchPosts(null, (posts) => {
        cb({
          posts: posts,
          user: user
        });
      });
    });