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.

0

1 Answer 1

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.

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

4 Comments

Thanks, it's working as expected.
How can I display uploaded images using angular js?
I am not much familiar with angular. But since you are saving images in the public folder, you can just use the public folder path in img src.
okay, thanks, I will try that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.