【问题标题】:Use distinct, or, skip, limit, AND sort in mongoose在 mongoose 中使用 distinct、or、skip、limit 和 sort
【发布时间】:2016-08-08 23:50:01
【问题描述】:

我正在尝试查找按时间戳排序的不同对话,条件是 senderuserIdrecipientuserId。我认为做到这一点的唯一方法是使用聚合。这就是我现在拥有的:

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

但是,我收到了一个“双重回调”错误(因此我注释掉了有问题的 $or 行。

伪代码(我想要实现的)是:

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

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    其中一些(如果不是全部)可以通过知道如何使用猫鼬的find来实现。

    然后,您应该订购这些命令。正确的顺序是:

    • sortlimit选项命令
    • $or 是一个条件命令,根据this
    • 最后,您必须将distinct 保留为单独的语句,因为它返回an array,并且不可链接。

    你最终会得到这个——理论上的——代码

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

    我鼓励您对其进行测试,但我不保证任何结果。希望对您有所帮助;)

    【讨论】:

    • 这不起作用。限制不能与 distinct 一起使用。
    • 实际上,任何options 语句都不能与 distinct 一起使用。我们必须找出“双重回调”是怎么回事。顺便说一句:你为​​什么在回调中使用返回?
    • @roscioli,你能给我一个测试数据集,让我找出解决方案吗?
    猜你喜欢
    • 2021-05-16
    • 2012-04-17
    • 2013-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-19
    • 2015-07-29
    • 2023-01-19
    相关资源
    最近更新 更多