0

I want to put a profile image into the users collection in mongodb, and I'd like to retrieve this image when user fetch his profile.

var storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, 'uploads/')
    },
    filename: (req, file, cb) => {
        cb(null, file.fieldname + '-' + Date.now()+ path.extname(file.originalname));
    }
});
var upload = multer({ storage: storage });
router.put('/user/profile/img/:email', upload.single('profileimg'), (req, res, next) => {
    // console.log(req.file);
    Users.findOneAndUpdate({ email: req.params.email }, req.file.filename).then(() => {
        Users.findOne({ email: req.params.email }).then((resp, err) => {
            res.send(resp);
        })
    })
})

Image is being saved in upload folder in my api but it's not saved in db.

Mickael B.
  • 4,755
  • 4
  • 24
  • 48

2 Answers2

2

The second parameter of the findOneAndUpdate function must be an object with the field to update and the value:

Users.findOneAndUpdate({ email: req.params.email }, { profileimg: req.file.filename }).then(...)

Mickael B.
  • 4,755
  • 4
  • 24
  • 48
-1

You can do it like this code below:

router.put('/user/profile/img/:email', upload.single('profileimg'), async (req, res, next) => {
  try {
    // check your file is uploaded
    // check your field
    console.log(req.file);
    const result = await Users.findOneAndUpdate({ email: req.params.email }, {$set: { profileimage : req.file.filename}}, { returnOriginal: false})
    res.send(result)
  } catch(ex) {
    res.status(500).send(ex.message);
  }
})

Note: For this {$set: { profileimage : req.file.filename}}

  • profileimage : change with the field in your mongodb
  • req.file.filename: make sure to console.log(req.file) then, where the field you want to store, use it in here and change this example.

I hope it can help you.

Titus Sutio Fanpula
  • 3,467
  • 4
  • 14
  • 33