I have this query in MongoDB
db.privateMessages.find(
{ $or : [
{fromId: userId, toId: socket.userId} ,
{fromId: socket.userId, toId: userId} ]
},
function(err, messages) { pushSvdMsgs(messages); });
It works perfectly, except for the fact that I get 50 results.
I have tried this:
db.privateMessages.find( { $or : [ {fromId: userId, toId: socket.userId} , {fromId: socket.userId, toId: userId} ] }, function(err, messages) { pushSvdMsgs(messages); }).limit(10);
But that didn't help either, so I tried this below which also didn't help limit it.
db.privateMessages.find( { $or : [ {fromId: userId, toId: socket.userId} , {fromId: socket.userId, toId: userId} ] }, { $limit : 2 }, function(err, messages) { pushSvdMsgs(messages); });
How can I limit the number of results from this query, and still call the callback the same way I have?
The limit() method in Mongoose is used to specify the number or a maximum number of documents to return from a query.
In MongoDB, the limit() method limits the number of records or documents that you want. It basically defines the max limit of records/documents that you want. Or in other words, this method uses on cursor to specify the maximum number of documents/ records the cursor will return.
All callbacks in Mongoose use the pattern: callback(error, result) . If an error occurs executing the query, the error parameter will contain an error document, and result will be null. If the query is successful, the error parameter will be null, and the result will be populated with the results of the query.
You got it almost right. Try this one:
db.privateMessages.find( { $or : [ {fromId: userId, toId: socket.userId} ,
{fromId: socket.userId, toId: userId} ] },
{},
{ limit : 2 },
function(err, messages) { pushSvdMsgs(messages); });
The syntax is find(query, fields, options)
. We need that empty object to make driver interpret options correctly.
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