Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating array of objects in MongoDb using SailsJS

I have a record in MongoDB in the following format:

  {
    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'
  }

I would like to update is_read inside status array. Here is what I have tried.

      Messages.update({
          thread: threadIds,
          status: { $elemMatch: { user: user.id, is_read: 0 } }
        },
        { $set: { "status.$.is_read": 1 } })

But same query runs really good in mongodb shell. Can anyone guide me if I am missing something? By the way I am running this query in SailsJS that uses Waterline ORM.

like image 698
Bilal Avatar asked Dec 10 '25 10:12

Bilal


1 Answers

To use the "same" query as the mongo shell, you'll have to use Model.native since Sails is based on Waterline, which has a slightly different query language from Mongo.

I haven't tried this, but I'd wager that this should do it:

  Messages.update({
      thread: threadIds,
      'status.user': user.id,
      'status.is_read': 0 
  },
  { 'status.is_read': 1 }, callback);
like image 141
galactocalypse Avatar answered Dec 13 '25 02:12

galactocalypse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!