简体   繁体   中英

Mongoose Query executed in for loop is not being pushed into an empty array after the for loop in finished executing, nodejs

Say, I have a model with an array of values incoming,

[ { _id: 5a69e13780e4172d514ed906, hobbyname: 'Teaching', __v: 0 },
{ _id: 5a69e1477a40892d6416f906, hobbyname: 'Cricket', __v: 0 }]

var arr = [];
    for(var i=0; i < someModel.length; i++){
    Hobby.find({})
       .then(function(hob){
           arr[i] = someModel[i].hobbyname;
       })
       .catch(function(err){
           console.log(err);
       });
    }
console.log(arr);

Presently its logging arr as [] , i would like it to finish the query execution, pushing the values to the arr and then give me the result.

I have simplified my project scenario, just to keep it understandable, i am a new bie, requiring help, thanks in advance.

All data processing should be in callback function

   Hobby.find({})
     .then(function(hob){
        console.log(hob);
        //here **hob** already contains the result of Mongo query - it's an array
        //so put your processing code here
     })
     .catch(function(err){
         console.log(err);
     });

if you want to catch data from Mongo by id or other condition you need to set such conditions in find query UPDATE: Or you may use async.waterfall to process data after aquiring it

async.waterfall(
  [
    function(callback) {    
     Hobby.find({})
       .then(function(hob){
          console.log(hob);
          return callback(null, hob);
       })
       .catch(function(err){
           console.log(err);
           return callback(err);
       });
    },
    function(hobbies, callback) {
      //here you get all retrieved hobbies to work on
      //**hobbies** - is result array
      //you may process it here

      return callback(null, hobbies);
    }
  ],
  function(err, result) {
    if (err) {
      console.log(err);

    }

    return next();
  }
);  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM