简体   繁体   中英

Use distinct, or, skip, limit, AND sort in mongoose

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM