Junaid Farooq Junaid Farooq - 2 months ago 7
Node.js Question

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

Answer Source

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);
    });
  }
}