Search code examples
mongoosefile-uploadmulter

How to remove certain unwanted response while uploading array of images in certain field of Schema using Mongoose?


This is Api for storing images.While storing images I want only pathname to get stored in DB rather than fieldname,sizes etc. And below is the response I am getting. I need only path to get stored in Db.Also while fetching I am getting this response which is of no use . Only image name or pathname is sufficient.

 const createStore = async (req,res,next) => {
            var id = req.params.tempid;
            var tempDetail = await Template.findById({_id:id})
        
            console.log("create store runnin,,,,,,,,")
           
            var store={
                "store_id":req.body.store_id,
                "store_name":req.body.store_name,
                "context": req.body.context,
                "display_image": req.body.display_image,
                "DisplayImage":req.files.DisplayImage,
                "DisplayLogo":req.files.DisplayLogo   
            }
            console.log("before store save")
            console.log(store)
            
            try{
              await Template.updateOne(
                { _id : id },
                { $push: { store:store }} 
            )

Response -

 {
      store_id: '1',
      store_name: 'sample',
      context: 'dmstore',
      display_image: 'chings',
      DisplayImage: [
        {
          fieldname: 'DisplayImage',
          originalname: '12345610.jpg',
          encoding: '7bit',
          mimetype: 'image/jpeg',
          destination: './template-store/temporaryImage',
          filename: '12345610.jpg',
          path: 'template-store\\temporaryImage\\12345610.jpg',
          size: 39955
        },
       ]

Blockquote


Solution

  • You can map through each image and take only path instead of entire object

    var store={
      "store_id":req.body.store_id,
      "store_name":req.body.store_name,
      "context": req.body.context,
      "display_image": req.body.display_image,
      "DisplayImage":req.files.DisplayImage.map(image => image.path),
      "DisplayLogo":req.files.DisplayLogo   
    }