Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On MongoDB how can I limit the query, when my callback is inside "find"?

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?

like image 315
user1306636 Avatar asked Apr 02 '12 03:04

user1306636


People also ask

What is limit in mongoose?

The limit() method in Mongoose is used to specify the number or a maximum number of documents to return from a query.

What is limit in MongoDB?

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.

What is callback in mongoose?

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.


1 Answers

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.

like image 94
Sergio Tulentsev Avatar answered Oct 16 '22 12:10

Sergio Tulentsev