Jan173 Jan173 - 11 months ago 68
Node.js Question

Nodejs: How to set limit when using Request module for mongodb

first question from my side, really excited! Have been following here a lot and you already helped a bunch, thanks for that!

Currently I am having some trouble with implementing a query limit for my mongodb when using the request module. I do have some queries which I stringify and attach to the URL which is being requested. However, setting a limit of how many results should be shown (as explained in the mongodb doc: https://mongodb.github.io/node-mongodb-native/markdown-docs/queries.html (see option)) is not doing the trick or at least I am putting it in the wrong place...

//request all countries that are in the database and push them into a search array

var query = JSON.stringify({'createdDate': {$gte: moment().subtract(5, 'days')}});

request(db_url + 'countries/?' + query, function(error, response, body) {}

trying to add:

var querylimit = {"limit": 20}

The mongodb doc gives the following example:

var options = {
"limit": 20,
"skip": 10,
"sort": "title"

collection.find({}, options).toArray(...);

Tried to add the querylimit behind the query (+query, querylimit), already in the stringify, stringified it itself and tried to add it etc.

I just cannot find a way to limit the query when using the request module.

Any help would be greatly appreciated!

Joe Joe
Answer Source

You need to do something like the following:

var limit = 20;
request(db_url + 'countries/?' + encodeURIComponent(query + "&limit=" + limit), function(error, response, body) {}

You are just appending the query options to the end of the URI.