On MongoDB how can I limit the query, when my callback is inside "find"?
Problem
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?
Problem courtesy of: user1306636
Solution
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.
Solution courtesy of: Sergio Tulentsev
Discussion
View additional discussion.