how do i format a multer image url in mongodb?

Your relPath variable needs to change

    const relPath = req.file.path.replace(remove,'')

Change it to the following

const relPath = req.file.path.replace(remove,'').replace(/\\/g, '/')

This extra replace added at the end will change all backward slashes into forward ones.

As a side improvement, you can change the replace(remove, '') to a slice

const skipCharactersCount = path.join(__dirname,'..','public').length
const relPath = req.file.path.slice(skipCharactersCount)

And since this skipCharactersCount never changes, you can save it as a constant outside of the function to avoid recomputing it every time.

Thus the replacement code would be like this:

const skipCharactersCount = path.join(__dirname,'..','public').length;
exports.create =  asyncHandler(async (req, res, next) => {
    const relPath = req.file.path.slice(skipCharactersCount).replace(/\\/g, '/')
    // rest can stay unchanged

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top