2

Is there a way I can use mongoose function inside a forEach loop like this example ? making use of the counter and reach the reachable line

   idsArray.forEach((itemId,i) =>{

        Place.findById(itemId,(err,item)=>{
            if(err){
                console.log("error")
            }
            idsArray[i] = {item.id}; // unreachable
        })
    })

I read about Async but I couldn't know the way to achieve it through it

1
  • you should return inside the if (error) statement, that could be one of the reasons you can't access to item.id. Maybe the query is failing but as you are not returning it keeps going even if there it was an error and item is undefined or null Commented Jun 15, 2017 at 14:21

2 Answers 2

3

Even simpler: map the elements with db promises, then wait for all of them:

var promises= idsArray.map((itemId,i) =>{
  return new Promise(function(resolve,reject){
    Place.findById(itemId,(err,item)=>{
        if(err){
           return reject(new Error("some"));
        }
        resolve(item);
    })
 });
});

Promises.all(promises).then(function(arr){
  console.log(arr);//all results
},function(err){
 throw err;
});
Sign up to request clarification or add additional context in comments.

Comments

1

I think Jonas w has the correct answer, but I'd like to show some minor variations, and the comment-area is not very useful.

var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');  // I like bluebird

// Using exec you get fully-fledged promises from the get-go.
var promises = idsArray.map( itemId => {
  return Place.findById(itemId).exec();
});

Promise.all(promises)
  .then( arr => { console.log(arr); } )
  .catch( err => { throw err; } );

1 Comment

This is actually the better way. I dont use mongoose so i didnt know of .exec() ... +1

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.