0


I am uploading images using MEAN stack and Multer module.
I am able to retrieve images from the angular, and can even post image-paths to Mongoose collection.

The problem is I am expecting an array of images but while posting to mongoose, it's storing each image as a new record.

Image schema

var imageSchema=new Schema({
    productId:{type: String,required: false},
    imagePaths: [{type: String, required: false}]
});



POST API

router.post('/upload', upload.any(), function(req , res){
  console.log('Executing Upload API..');
    console.log(req.body);
    console.log(req.files);
    var images = req.files;

req.files.forEach(function(file){
      var filename = (new Date()).valueOf() + '-' + file.originalname;
      fs.rename(file.path,'public/images/'+ filename, function(err){
       // if (err) throw err;
        //Save to mongoose

        var image = new Image({
          productId: 1007,
          imagePaths: filename
        });
        image.save(function(err, result){
          if(err) throw err;
            res.json(result);
        });
        console.log('FileName :' + filename);

      });
    });
});



Collection saved
If I post 2 images, it's getting stored as shown below, but I want both the images to be sotred in same record, i.e inside imagePaths:.

**

{
        "_id" : ObjectId("59abab004783d90bccb4a723"),
        "productId" : "1007",
        "imagePaths" : [
                "1504422656691-Screenshot (4).png"
        ],
        "__v" : 0
}
{
        "_id" : ObjectId("59abab004783d90bccb4a724"),
        "productId" : "1007",
        "imagePaths" : [
                "1504422656691-Screenshot (3).png"
        ],
        "__v" : 0
}

**
Please help.

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
mayank bisht
  • 618
  • 3
  • 14
  • 43

1 Answers1

0

In your forEach, you are creating new record for every file with new Image, rather what you should be doing is create an array of all the filename and make the record once. Maybe this piece of code will help you.

router.post('/upload', upload.any(), function(req , res){
  console.log('Executing Upload API..');
  console.log(req.body);
  console.log(req.files);
  var images = req.files;

  const filePromises = req.files.map(function(file){
    var filename = (new Date()).valueOf() + '-' + file.originalname;
    console.log('FileName :' + filename);

    return new Promise(function(resolve, reject) {

      fs.rename(file.path,'public/images/'+ filename, function(err) {
        if (err) return reject(err);
        return resolve(filename);
      });
    });

  });

  Promise.all(filePromises)
  .then( fileNames => {

    var image = new Image({
      productId: 1007,
      imagePaths: fileNames
    });

    image.save(function(err, result){
      if(err) throw err;
      res.json(result);
    });
  })

});

In this I have created the array of promises which will contain filename, and then resolving all of them using Promise.all to finally get the resolved array of filename, which then I can simply pass to create a new record.

Raghav Garg
  • 3,601
  • 2
  • 23
  • 32