2016-10-01 67 views
0

我想從我的「聊天」集合中獲取所有文檔。當我循環訪問結果變量和控制檯日誌項時,我得到很多數據。我如何查詢所有對象並獲取文檔字段?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

你的控制檯是什麼?並且你想要哪些字段請詳細說明它 –

回答

2

您需要一個投影來實現這一點。

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

額外的數據來自我的控制檯登錄我的路線。我是控制檯記錄回調,所以它打印的結果對象。 –