Noah
Noah

Reputation: 4751

'the limit must be specified as a number' error when using req.query.property

I'm doing a Mongoose/MongoDB .aggregate query with $limit in the pipeline. When I use a number, like 2, it works fine. If I set a variable like testNum = 2, and then do {$limit: varNum}, it works fine. But if I send a REST query and try do $limit: req.body.show, it says the value is not a number.

I can see the value is a number through console.log. The other queries in the pipeline don't complain that they're not given numbers. Here is the code:

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

The query here is ?show=2&page=1. The console output is 2 0 1. That is working right.

The full error is here:

{ [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 }

Upvotes: 5

Views: 6399

Answers (2)

godzsa
godzsa

Reputation: 2395

You can use the unary + operator too. +req.query.show

Upvotes: 4

Noah
Noah

Reputation: 4751

For some reason show is being treated like a string in the case of $limit, but nothing else seems to mind. I did this to fix it, but I think this might be a bug with Express or Mongoose/MongoDB. If anyone knows where to bring this up, let me know.

The fix is to use parseInt like this:

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

Upvotes: 9

Related Questions