【问题标题】:Node.js: Range Query in MongoDB with multiple criteria, using MongooseNode.js:使用 Mongoose 在 MongoDB 中使用多个条件进行范围查询
【发布时间】:2018-09-29 00:50:18
【问题描述】:

我正在尝试使用 Mongoose 在 MongoDB 中实现“范围查询”,按“标准”排序,然后按“_id”排序。 我想向客户端返回一个包含两个游标的字符串。

我试图用注释块 2 来实现类似下面的代码。但是,我遇到了一个错误。甚至没有打印日志消息。

在我的测试中,查询是空的,因为集合是空的。 我怀疑我没有得到光标,所以我用'block 1'而不是block 2进行了测试,它工作了。 但是由于我需要最后一个光标,我想我真正需要使用的是 .toArray 方法,对吧?

我做错了什么?

    Feed.find({
        "criteria": {$lt: cursorCriteria},
        "_id": {$lt: cursorId}
    })
    .sort({ 
        criteria: -1,
        _id: -1 
    })
    .limit( 50 )

    // block 1: just to test if I'm getting the cursor 
    .then( items => {
        items.forEach( function(item) {
            console.log('an item');
        })
    })

    /* block 2:  if I try this block instead of block 1, I get an error
    .toArray( items => {
        if (items.length > 0) {
            console.log('not empty);
        } else {
            console.log('empty');
        }
        var nextCursor = '${item.criteria}_${item._id}';
        res.status(200).json({item, nextCursor});
    })
    */

【问题讨论】:

  • 错误是什么...
  • "RangeError: 无效状态码:未定义"
  • 我以为我找到了答案,但没有.. RangeError 仍然存在.. :-/

标签: mongodb mongoose


【解决方案1】:

Mongoose 没有 toArray() 方法 这很好用:

 .then( items => {
                if (items.length > 0) {
                    console.log('not empty');
                } else {
                    console.log('empty');
                }
                var nextCursor;
                if (items.length > 0) {
                    nextCursor = '' + items[items.length-1].criteria + "_" + items[items.length-1]._id;
                } else {
                    nextCursor = '';
                }
                res.status(200).json({items, nextCursor});
            })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-13
    • 1970-01-01
    • 2012-12-09
    • 1970-01-01
    • 2011-07-28
    • 2021-10-23
    • 1970-01-01
    相关资源
    最近更新 更多