Junaid Farooq
Junaid Farooq

Reputation: 2598

Adding mongoose object to array in nodejs

I have an array of images as this.

  var newImageParams = [
    {
      image_string: "hello",
      _type: "NORMAL"
    },
    {
      image_string: "hello",
      _type: "NORMAL"
    }
  ]

I am using mongo db and In nodejs, I am using mongoose, Everything is fine, I Can add data to mongoose table, but after adding each image, I am trying to save the resulting object into an array, Which in console.log is happening and right as well, but when I return that array, there is nothing in it and it empty

if (newImageParams) {
  for (var i = newImageParams.length - 1; i >= 0; i--) {
    // allImages[i]
    var newImage = new Image(Object.assign(newImageParams[i], {bike: bike._id}));
    newImage.save(function(err, image){
      console.log(image);
      allImages.push(image);
      console.log(allImages);
    });
  }
}

This is what I am doing, everything is right and good in console but when I finally return,

res.json({bike: bike, images: allImages });

Images array is totally empty as it was when declared? why this is happening, please help

Upvotes: 1

Views: 68

Answers (2)

HuyTran
HuyTran

Reputation: 153

allImages.push(image); -> that line of code is async. It's will go to event queue and your console log will call immediately.

So console.log(allImages); will return empty.

You can read more in here. It will help you in future.

Upvotes: 0

Lazyexpert
Lazyexpert

Reputation: 3154

I bet you send response before your callbacks are done.

The easy and fast fix:

if (newImageParams) {
  for (var i = newImageParams.length - 1; i >= 0; i--) {
    const image = Object.assign(newImageParams[i], {bike: bike._id});
    var newImage = new Image(image);
    allImages.push(image);
    newImage.save(function(err, image){
      console.log(image);
      console.log(allImages);
    });
  }
}

I will add correct approach with async/await, the older versions would use Promise.all or async.parallel:

async function doJob() {
  if (newImageParams) {
    for (var i = newImageParams.length - 1; i >= 0; i--) {
      const image = Object.assign(newImageParams[i], {bike: bike._id});
      const newImage = new Image(image);      
      await newImage.save();
      allImages.push(image);
    }
  }
}

Upvotes: 2

Related Questions