Friday, 7 September 2018

save form with files and body using Multer into MongoDb

I am trying to save the files at that path and save the name of the files and also the other inputs in a Mongo collection so I can pick them up later this is my modelvar mongoose = require('mongoose'); var Schema = mongoose.Schema; var ImageSchema = new Schema({ filename: String, destination: String }) var ProductSchema = new Schema({ make: String, model: String, . . . details: String, images: ImageSchema }); module.exports = mongoose.model('Car', ProductSchema); add.pug form(method='post', action='/add', enctype="multipart/form-data") legend Add car .row .col-lg-6.mx-auto .form-group label(for='make') Make input#make.form-control(type='text') ... .row input(type='file', name='userPhoto' multiple) button#addbutton.btn.btn-primary.float-right(value="Submit" type="submit") Submit add.jsvar multer = require('multer'); var upload = multer({ dest: 'public/images/cars' }) mongoose.connect('mongodb://localhost:27017/myDb'); var storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, './public/images/cars'); }, filename: function (req, file, cb) { var originalname = file.originalname; var extension = originalname.split("."); filename = Date.now() + '.' + extension[extension.length-1]; cb(null, filename); } }); router.post('/', multer({storage: storage, dest: './public/images/cars'}).array('userPhoto',4), function(req,res) { console.log(req.files); var document = { make: req.body.make, model: req.body.model, details: req.body.details, images: '' }; console.log(req.files); var files = req.files; files.forEach(function(element) { document.images.filename = element.filename; document.images.filename = element.path; }); var car = new Car(document); console.log(car); car.save(function (err) { if (err){console.log(err)} else { res.redirect('/'); } }); }); keep getting req.files undefined (also there are more form fields i cut some of them)

Submitted September 08, 2018 at 03:58AM by shiust

No comments:

Post a Comment