0

How can i use the for loop with findOne from mongoose in node.js, maybe have other logic that i can do the same thing?

    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);  

                        }          

                });
            }
John
  • 483
  • 3
  • 9
  • 18
  • 3
    Possible duplicate of [mongodb/mongoose findMany - find all documents with IDs listed in array](https://stackoverflow.com/questions/8303900/mongodb-mongoose-findmany-find-all-documents-with-ids-listed-in-array) – dnickless Aug 22 '17 at 19:02

1 Answers1

0

If you can transform your input data into an array you can do this:

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

Message.find({from: {$in: data}, to:socket.handshake.session.passport.user})
dnickless
  • 10,733
  • 1
  • 19
  • 34