2017-08-22 114 views
0

如何在node.js中使用mongoose中的findOne for for循環,也許有其他邏輯可以做同樣的事情?Node.JS Mongoose findOne With for循環

data = { _id: '598b4e9abe74280be0b0cb1b' } 
      { _id: '598b4ec1be74280be0b0cb1c' } 
      { _id: '598b4fa8be74280be0b0cb1d' } 
      { _id: '5992feccdad6db0c603b260d' } 
      { _id: '5995e4ce0b38ba123cf06654' }; 

    notification = new Array(); 

    for (var i = 0; i < data.length; i++) { 
       Message.findOne({ from: data[i]._id, to:socket.handshake.session.passport.user }, function(err, message){ 

         if (err){ 

          console.log('error'); 

         } 

         if(!message.length){ 

          console.log('no message!!'); 

         }else{ 

          notification.push(message); 

         }   

       }); 
      } 
+3

的可能的複製[MongoDB中/獴findMany - 找到在數組中列出的ID的所有文件(HTTPS:/ /stackoverflow.com/questions/8303900/mongodb-mongoose-findmany-find-all-documents-with-ids-listed-in-array) – dnickless

回答

0

如果您可以將您的數據輸入到一個數組,你可以這樣做:

var data = [ObjectId('598b4e9abe74280be0b0cb1b'), 
      ObjectId('598b4ec1be74280be0b0cb1c'), 
      ObjectId('598b4fa8be74280be0b0cb1d'), 
      ObjectId('5992feccdad6db0c603b260d'), 
      ObjectId('5995e4ce0b38ba123cf06654')]; 

Message.find({from: {$in: data}, to:socket.handshake.session.passport.user})