MongoDB返回大量数据

问题描述:

我想从我的“聊天”集合中获取所有文档。当我循环访问结果变量和控制台日志项时,我得到很多数据。我如何查询所有对象并获取文档字段?MongoDB返回大量数据

//create route 
router.get('/', function(req, res) { 

    db.connect(url, function(err, db){ 
     if(err){ 
      console.log(err); 
     }else{ 
      console.log("Connected"); 
     } 

     getAllChats(db, function(data){ 
      console.log(data); 
     }); 

    }); 

    res.render('index.jade'); 
}); 

var getAllChats = function(db, callback){ 

    var collection = db.collection('chats'); 
    var results = collection.find(); 

    results.each(function(err, item) { 
     // If the item is null then the cursor is exhausted/empty and closed 
     console.log(item); 
     if(item == null) { 
      db.close(); // you may not want to close the DB if you have more code.... 
      return; 
     } 
     // otherwise, do something with the item 
    }); 
    callback(results); 
} 
+0

你是什么意思“只获取文档字段”?你能提供一个你想排除的被返回数据的例子吗? –

+0

你的控制台是什么?并且你想要哪些字段请详细说明它 –

您需要一个投影来实现这一点。

https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/

var collection = db.collection('chats'); 
var results = collection.find(query, projection); 

在你的情况的查询将是{}; 投影将是{FieldYouNeed: 1, fieldYouNeed: 1, ...};

这里是例子

var results = collection.find({name: "developer"}, {_id: 0, name: 1, email:1}); 

在这种情况下,只有nameemail将DB返回。

希望这会有所帮助。

+0

即使当我传递查询的空对象并指定我需要的值为1的字段时,我仍然会得到一个巨大的对象。我可以看到返回对象底部的结果。 –

+0

额外的数据来自我的控制台登录我的路线。我是控制台记录回调,所以它打印的结果对象。 –