在MongoDB上,当我的回调在"find"内时,如何限制查询?

use*_*636 9 mongodb node.js

我在MongoDB中有这个查询

db.privateMessages.find( 
    { $or : [ 
       {fromId: userId, toId: socket.userId} , 
       {fromId: socket.userId, toId: userId} ] 
    }, 
    function(err, messages) { pushSvdMsgs(messages); });
Run Code Online (Sandbox Code Playgroud)

除了我获得50个结果这一事实外,它完美无缺.

我试过这个:

db.privateMessages.find( { $or : [ {fromId: userId, toId: socket.userId} , {fromId: socket.userId, toId: userId} ] }, function(err, messages) { pushSvdMsgs(messages); }).limit(10);
Run Code Online (Sandbox Code Playgroud)

但这也没有帮助,所以我在下面尝试了这个也没有帮助限制它.

db.privateMessages.find( { $or : [ {fromId: userId, toId: socket.userId} , {fromId: socket.userId, toId: userId} ] }, { $limit : 2 }, function(err, messages) { pushSvdMsgs(messages); });
Run Code Online (Sandbox Code Playgroud)

如何限制此查询的结果数量,仍然以与我相同的方式调用回调?

Ser*_*sev 22

你得到它几乎是正确的.试试这个:

db.privateMessages.find( { $or : [ {fromId: userId, toId: socket.userId} , 
                                   {fromId: socket.userId, toId: userId} ] },
                         {}, 
                         { limit : 2 }, 
                         function(err, messages) { pushSvdMsgs(messages); });
Run Code Online (Sandbox Code Playgroud)

语法是find(query, fields, options).我们需要该空对象来正确地创建驱动程序解释选项.

  • "空对象"用于排除结果集中返回的特定字段. (3认同)