Search code examples
node.jsmongoosemulter

Storing image path string to db with Multer & Mongoose


I am trying to save the key > imageItem: value to the DB. Somehow the field is not created in the MongoDB other key-value fields are created without issue..

I have found some similar questions here but none of them had a complete answer. I tried a number of things such as > itemImage:{ Type:String } etc.

Form:

<form action="/insert" method="POST" enctype="multipart/form-data">
            <input type="text" placeholder="title" name="title">
            <input type="text" placeholder="director" name="director">
            <input type="text" placeholder="year" name="year">
            <input type="file" placeholder="movie-image-multer" accept="image/*" name="image" >
<button type="submit">Save movie</button>
</form>

in Router:

const multer= require('multer')

const storage = multer.diskStorage({
  destination: function(req, file, cb){
    cb( null, './public/images');
  },
  filename: function(req, file, cb){
    cb( null, Date.now() + file.originalname);
  },
})


const upload = multer({
  storage: storage,
  limits:{
    fieldSize:1024 * 1024 * 3,
  },
})


router.post('/insert',upload.single('image'), (req, res) => {
  var newItem = new Article({
    title: req.body.title,
    director: req.body.director,
    year: req.body.year,
    image: req.file.filename
  })
  newItem.save((err, doc) => {
    if (!err) {
      res.redirect('insert');
      console.log(req.file.filename);
    }
    else {
      console.log(err);
    }
  });
});

Model:

const mongoose = require('mongoose')

var Schema = mongoose.Schema;
var articleSchema = new Schema({
    title:  { type: String, required: true },
    director: { type: String },
    year: { type: String },
    image:{  
        data: Buffer,
        contentType: String
     }
});

articleSchema.set('timestamps', true);
const Article = mongoose.model('Article', articleSchema)
module.exports = Article;

Solution

  • Ok.. got it finaly, I used image:{ Type: String } instead of image: { type:String } in the model. Thanks for pointing me in that direction @Sebastián Espinosa

    Updated the model as such:

    const mongoose = require('mongoose')
    
    var Schema = mongoose.Schema;
    var articleSchema = new Schema({
        title:  { type: String, required: true },
        director: { type: String },
        year: { type: String },
        image:{  
            type: String
         }
    });
    
    articleSchema.set('timestamps', true);
    const Article = mongoose.model('Article', articleSchema)
    module.exports = Article;