使用SailsJS更新MongoDb中的对象数组

3

我在MongoDB中有以下格式的记录:

  {
    attachment: 'xxxxxxx',
    createdAt: TueAug04201514: 52: 23GMT+0400(GST),
    text: 'xxxxxxx',
    sender: '55784247c95c59cc746904e1',
    status: [
      {
        user: '5589464675fc0892757d170e',
        is_read: 0
      },
      {
        user: '55a4a39d5c0bf23d21e6c485',
        is_read: 0
      },
      {
        user: '55a4a38e5c0bf23d21e6c483',
        is_read: 0
      },
      {
        is_read: 0,
        user: '55784247c95c59cc746904e1'
      }
    ],
    thread: '55c0946b80320adb3fd04d0e',
    updatedAt: TueAug04201515: 45: 55GMT+0400(GST),
    id: '55c09967708b73184558fbc8'
  }

我想更新status数组内的is_read。以下是我的尝试。
      Messages.update({
          thread: threadIds,
          status: { $elemMatch: { user: user.id, is_read: 0 } }
        },
        { $set: { "status.$.is_read": 1 } })

但是相同的查询在mongodb shell中运行得非常好。有人能指导我是否遗漏了什么吗?顺便说一下,我正在SailsJS中运行此查询,它使用Waterline ORM


Message 模型和其 status 属性之间有什么关系? - Yann Bertrand
我无法理解你所指的“关系”。 “状态”是“Message”模型的一个带有“数组”类型的属性。 - Bilal
2个回答

3
要使用与mongo shell相同的查询,您需要使用Model.native,因为Sails基于Waterline,它的查询语言与Mongo略有不同。我没有尝试过这个,但我敢打赌应该可以做到:
  Messages.update({
      thread: threadIds,
      'status.user': user.id,
      'status.is_read': 0 
  },
  { 'status.is_read': 1 }, callback);

是的,你说得对,我使用了 Model.native 解决了这个问题,但是你发布的代码是错误的。 - Bilal
我很高兴你这么做了。就像我说的,我还没有尝试过这段代码。你能告诉我哪里出了问题,这样我就可以更新它吗? - galactocalypse
“'status.user': user: user.id,” 这里有一个语法错误。只能有一个键和它的值对应。 - Bilal

0
这是我是如何解决这个问题的。
     // You have to use {model_name}.mongo.objectId() for ids otherwise your
     // query will not work.
     threadIds.push(Messages.mongo.objectId(thread.id));

     Messages.native(function (err, collection ) {

        if (err) {
          return res.send(500, err);
        }

        collection.update({
            thread: {$in: threadIds},
            status: {
              $elemMatch: {
                user: user.id,
                is_read: 0
              }
            }
          },
          {
            $set: {"status.$.is_read": 1}
          }, function (err, messages) {

            if (err) {
              return res.send(500, err);
            }

            return res.send(200);

          });

      });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接