0

I need to create a new array from iterating mongodb result. This is my code.

const result = await this.collection.find({
  referenceIds: {
    $in: [referenceId]
  }
});

var profiles = [];

result.forEach(row => {
  var profile = new HorseProfileModel(row);

  profiles.push(profile);

  console.log(profiles); //1st log
});

console.log(profiles); //2nd log

I can see update of profiles array in 1st log. But 2nd log print only empty array.

Why i couldn't push item to array?

Update I think this is not related to promises. HorseProfileModel class is simply format the code.

const uuid = require("uuid");

class HorseProfileModel {

    constructor(json, referenceId) {

        this.id = json.id || uuid.v4();
        this.referenceIds = json.referenceIds || [referenceId];
        this.name = json.name;
        this.nickName = json.nickName;
        this.gender = json.gender;
        this.yearOfBirth = json.yearOfBirth;
        this.relations = json.relations;
        this.location = json.location;
        this.profilePicture = json.profilePicture;
        this.horseCategory = json.horseCategory;
        this.followers = json.followers || [];
    }

}

module.exports = HorseProfileModel;
6
  • 2
    @Rajesh No he is pushing a new profile into a profile list... Commented Sep 29, 2017 at 8:58
  • 3
    Is forEach Array.prototype.forEach or is it the MongoDB version ? Commented Sep 29, 2017 at 8:58
  • Possible duplicate of Wait till all items from mongoDB query are processed before continuing Commented Sep 29, 2017 at 8:59
  • Why don't you try the cursor's map() method as let profiles = result.map(r => new HorseProfileModel(r))? Commented Sep 29, 2017 at 9:05
  • 1
    @jonasw got it what you mean. Thanks. I'll not comment like that. Commented Sep 29, 2017 at 9:20

1 Answer 1

3
 await this.collection.find(...)

that returns an array of the found data right? Nope, that would be to easy. find immeadiately returns a Cursor. Calling forEach onto that does not call the sync Array.forEach but rather Cursor.forEach which is async and weve got a race problem. The solution would be promisifying the cursor to its result:

const result = await this.collection.find(...).toArray();

Reference

Sign up to request clarification or add additional context in comments.

Comments

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.