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

Updating array of objects in MongoDb using SailsJS

我在 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.

要将 "same" 查询用作 mongo shell,您必须使用 Model.native,因为 Sails 基于 Waterline,它与 Waterline 略有不同来自 Mongo.

的查询语言

我没试过这个,但我敢打赌这应该能做到:

  Messages.update({
      thread: threadIds,
      'status.user': user.id,
      'status.is_read': 0 
  },
  { 'status.is_read': 1 }, callback);

这就是我解决这个问题的方法。

     // 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);

          });

      });