How can i store image url in mongodb collection?

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???

Hi @Naila_Nosheen

Unfortunately I have zero knowledge of Multer, and I would assume most people in this forum as well, as this is a MongoDB-specific forum :slight_smile:

However I found an article that may be of help for you: Image Uploading to MongoDb in Nodejs using Multer. The article in question is using a buffer as I think it intends to store the image binary itself, rather than the image URL as you need. You might need to modify this part a little to fit your purpose. Hopefully this will point you to the right direction.

Best regards
Kevin

Thank you so much for your link :slight_smile:

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.