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.

1

2 Answers 2

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(...)

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

4 Comments

What's the result of the function call ?
getting responce as users json with an empty profileimg field.
Yes you need to put the correct field name in the second parameter. I've edited.
We need more details then, there is probably an error somewhere else in your code.
-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.

15 Comments

changed the name to profileimage but still not working
When you console.log(req.file), what the object you get?
{ fieldname: 'profileimg', originalname: '1.png', encoding: '7bit', mimetype: 'image/png', destination: 'uploads/', filename: 'profileimg-1580208697681.png', path: 'uploads\\profileimg-1580208697681.png', size: 3368 }
I've been update my code in my answer. you can try it. I hope you copy code above and replace yours
the $set is unnecessary cus mongoose takes care of it internally.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.