I'm using node, express and multer to upload files in angular application while having mongoDB for the database. When I'm uploading a file, although it's getting uploaded in the destination folder called uploads which I declared as static in my index.js, it's path where the file is saved is not shown in the database and remains blank as a default value. Below is a snap of my database when the form is created and the image is also uploaded but the imagePath field where the location should be remains blank
{
"title": "title to check file upload second time",
"description": "checking file upload check",
"bodyHtml": "",
"views": 0,
"isPublished": true,
"category": "Drama",
"author": "",
"imagePath": "",
"_id": "5e399bd4de5df134604a662f",
"blogId": "ZSiEu37z",
"created": "2020-02-04T16:29:08.000Z",
"lastModified": "2020-02-04T16:29:08.000Z",
"__v": 0
}
multer settings on the controller:
const multer = require('multer')
const storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, './uploads/')
},
filename: function(req, file, cb) {
cb(null, Date.now() + file.originalname)
}
})
const upload = multer({storage: storage})
let setRouter = (app) => {
let baseUrl = appConfig.apiVersion+'/blogs';
app.post(baseUrl+'/create', upload.single('imagePath'), (req, res) => {
var today = time.now()
let blogId = shortid.generate()
let newBlog = new BlogModel({
blogId: blogId,
title: req.body.title,
description: req.body.description,
imagePath: req.body.imagePath
}) // end new blog model
newBlog.save((err, result) => {
if (err) {
console.log(err)
res.send(err)
} else {
res.send(result)
}
}) // end new blog save
})
blog model
// importing mongoose module
const mongoose = require('mongoose')
// import schema
const Schema = mongoose.Schema;
let blogSchema = new Schema(
{
blogId: {
type: String,
unique: true,
index: true
},
title: {
type: String,
default: ''
},
description: {
type: String,
default: ''
},
imagePath: {
type: String,
default: ''
}
}
)
mongoose.model('Blog', blogSchema);
inside controller function while saving the json object use req.file.path instead of req.body.imagePath as a value of imagePath