简体   繁体   中英

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

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!

Welcome to StackOverflow @Jan173

You can't contact new object to stringified object.

Instead you can convert your string to object using JSON.parse and add your query limit into the same object

var queryObj = JSON.parse(query); // stringify query converted to object
queryObj.limit = 20; // adding new propery limit to query object
collection.find({}, queryObj); // fetch data with query object

Hope this will work, Happy coding :)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM