2016-10-01 1 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, ...}です。ここ

のみnameemail DBから返されます。この場合の例

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

あります。

これが役に立ちます。

+0

クエリの空のオブジェクトを渡して、値1で必要なフィールドを指定しても、まだ大きなオブジェクトが戻ってきます。返されたオブジェクトの最後に結果が表示されます。 –

+0

私のルートのコンソールログから余分なデータが送られてきました。コールバックをログに記録して結果オブジェクトを出力していました。 –

関連する問題