0

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.

1 Answer 1

1

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();
  }
);  
Sign up to request clarification or add additional context in comments.

3 Comments

thx for your reply, but i want to know how to push a query result in a for loop into an empty array. i want the for loop to wait for the complete query execution, store the values in an array one by one, and then print the array outside the array. Please help me or atleast let me know how to do callbacks.
again - after executing query - function will return resulting array with all fetched records in hob arrays, so you need to put your code for record processing instead of comments I've added //here **hob** already contains the result of Mongo query - it's an array //so put your processing code here Take a look at this comprehensive example of using MongoDB with NodeJS/Express
I want the result to be used outside. Like, when i console.log(arr); i have to get the output process inside for loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.