Hello, I want to store the image URL in my MongoDB collection using multer and machine storage. I tried to follow one tutorial but it is not generating the correct URL I am posting my code here too. Can someone please guide me? I am very new to storing data in the database.
This is my model file:
[const mongoose = require('mongoose');
const User = mongoose.model('User', new mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
profilePictureURL: {
type: String
}
}));
exports.User = User;](https://)
This is my multer middleware:
const store = multer.diskStorage({
destination: function (req, file, cb) {
fs.mkdir(path, { recursive: true}, function (err) {
if (err) return cb(err);
cb(null, "uploads/photos");
});
},
filename: function (req, file, cb) {
const name = file.originalname.toLowerCase().split(' ').join('_');
cb(null, name + '-' + Date.now());
}
});
const upload = multer({ storage: store }).single('file');
This is my post router:
function CreateUser(req, res) {
const url = req.protocol + '://' + req.get("host");
let user = new User(
{
name: req.body.name,
email: req.body.email,
image: url + '/uploads/photo/' + req.file.filename
}
);
user.save()
.then(data => {
res.send(data);
}).catch(err => {
res.status(500).send({
success: false,
message: err.message || "Some error occurred while creating the user."
});
});
};
router.post('/create', [upload], CreateUser);
Can anyone please help me with this code???