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 }
query is a request object that is populated by request query strings that are found in a URL. These query strings are in key-value form. They start after the question mark in any URL.
req. query contains the query params of the request. req. body contains anything in the request body.
req.paramsAn object containing properties mapped to the named route “parameters”. For example, if you have the route /user/:name, then the "name" property is available as req.params.name.
Both are closely related but they are not the same at all, params are parameters set for the route, query are values resembling variable assignment that provide extra information on what is being required for the route and it will always start with a ? on the URL, inherently they are both string values that express ...
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With