0

I am trying to find distinct conversations sorted by timestamp and with conditions that sender is userId or recipient is userId. I think the only way to do this is with aggregations. This is what I have right now:

Notification.aggregate([
        // { $or: [ { $sender: userId }, { $recipient: userId } ] },
        { $group: { _id: '$conversationId' } },
        { $skip: (page - 1) * LIMIT },
        { $limit: LIMIT },
        { $sort: { timestamp: 1 } }
    ], function (err, result) {
        // console.log(result);
        return result;
    });

However, I am getting a "double callback" error with this (hence why I commented out the offending $or line.

The pseudocode (that I am trying to achieve) is:

Notification.find().or([
    { sender: userId },
    { recipient: userId }
])
.distinct('conversationId')
.sort('-timestamp')
.limit(LIMIT)
.skip((page - 1) * LIMIT)
.exec(function (error, result) {
    return result;
});
roscioli
  • 1,200
  • 3
  • 15
  • 33

1 Answers1

-1

Some of these things (if not all) can be achieved through knowing how to use mongoose's find.

Then, you should order these commands. The correct order is:

  • sort and limit are options commands
  • $or is a conditions command, according to this
  • Finally, you must leave distinct as a separated statement, since it returns an array, and is not chainable.

You'll end up having this –theoretical– piece of code

Notification.find({
    $or: [
        sender: userId,
        recipient: userId
    ]
}, undefined, {
    skip: (page - 1) * LIMIT,
    limit: LIMIT,
    sort: {
        timestamp: 1
    }
}).distinct('conversationId', (err, results) => {
    // ***
});

I encourage you to test it, however I'm not assuring any results. Hope it helps ;)

Community
  • 1
  • 1
pandres95
  • 183
  • 1
  • 9
  • 2
    This does not work. Limit cannot be used with distinct. – roscioli Apr 17 '16 at 08:09
  • Actually, any of the `options` statements can't be used along with distinct. We'd have to find out what's going on with the "double callback" thing. By the way: why are you using a return inside a callback? – pandres95 Apr 17 '16 at 08:15
  • @roscioli, can you give me a test set of data, so I can figure out a solution? – pandres95 Apr 17 '16 at 08:34