使用 Multer 和 Mongoose 将图像路径字符串存储到数据库

Storing image path string to db with Multer & Mongoose

我正在尝试将键 > imageItem: 值保存到数据库中。不知何故,该字段未在 MongoDB 中创建 其他键值字段的创建没有问题..

我在这里发现了一些类似的问题,但其中 none 有完整的答案。 我尝试了很多东西,例如 > itemImage:{ Type:String } 等等

形式:

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

在路由器中:

const multer=要求('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);
    }
  });
});

型号:

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;

好的.. 终于明白了,我在模型中使用了 image:{ Type: String } 而不是 image: { type:String } 。 谢谢你给我指点@Sebastián Espinosa

更新模型如下:

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;