使用 req.query.property 时出现'the limit must be specified as a number'错误



我正在使用管道中的$limit执行Mongoose/MongoDB .aggregate查询。当我使用像2这样的数字时,它工作得很好。如果我设置一个像testNum = 2这样的变量,然后执行{$limit: varNum},它就可以正常工作。但是,如果我发送一个REST查询并尝试执行$limit: req.body.show,它会显示该值不是数字。

我可以通过console.log看到这个值是一个数字。管道中的其他查询不会抱怨没有给出数字。这是代码:

var show = req.query.show,  // the number of items to show per page
    page = req.query.page,  // the current page being asked for
    stream = req.params.stream, // the type of content to get
    skip = ( page > 0 ? (( page - 1 ) * show ) : 0 ), // amount to skip
    testNum = 3
console.log( show + " " + skip + " " + page )
Content.aggregate( [
    { $unwind: '$users' },
    { $group: { 
        _id: '$_id',
        title: { $first: '$title' },
        description: { $first: '$description' },
        images: { $first: '$images' },
        url: { $first: '$url' },
        saveCount: { $sum: 1 } } 
    },
    { $sort: { saveCount: -1 } },
    { $skip: skip },
    { $limit: show }
] )
.exec()

这里的查询是?show=2&page=1。控制台输出为2 0 1。这是正确的。

完整的错误在这里:

{ [MongoError: exception: the limit must be specified as a number]
name: 'MongoError',
errmsg: 'exception: the limit must be specified as a number',
code: 15957,
ok: 0 }

由于某种原因,show$limit的情况下被视为字符串,但似乎不介意其他任何事情。我这样做是为了修复它,但我认为这可能是Express或Mongoose/MongoDB的一个错误。如果有人知道在哪里提起这个,请告诉我。

修复方法是像这样使用parseInt

var show = parseInt( req.query.show ),  // the number of items to show per page

您也可以使用一元+运算符。+req.query.show

相关内容

最新更新