Saving image with mongoose Saving image with mongoose mongodb mongodb

Saving image with mongoose


You know, definitely it's not the best way to save image data on mongo. Instead you can save your image on any directory on your server and save only url of your file, like..

mongoose-model.js

avatar : {    type : String}

and on your main script you should get

let avatar_url = '/path/to/uploads/' + req.body.data.image.file.name

something like this


If you are using express than you can use express-fileupload middleware to upload files.

const fileUpload = require('express-fileupload');app.post('/upload', fileUpload, (req, res) => {  //Now you can use req.files.file to access the file input with name="file"  user.avatar = {data: req.files.file.data, contentType: req.files.file.mimetype};  //Now perform user.save})


It seems that your issue is not related to the image.

According to your code, the error message TypeError: Cannot set property 'avatar' of null means that the variable user is null.

And user is the result of findById(index.findUserId(req)).

So you should try to understand why this part is returning null.