【问题标题】:Storing image path string to db with Multer & Mongoose使用 Multer 和 Mongoose 将图像路径字符串存储到 db
【发布时间】:2021-05-01 19:40:12
【问题描述】:

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

我在这里发现了一些类似的问题,但没有一个有完整的答案。 我尝试了很多方法,例如 > 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= 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);
    }
  });
});

型号:

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;

【问题讨论】:

  • 您正在保存文件名,但在您的模型中,您需要一个数据缓冲区和一个内容类型
  • 字段名称在 html name="itemImage"upload.single('image') 中不同。
  • @turivishal 更新了图像相同结果的问题..
  • @Sebastián Espinosa 我也试过 > image: { type: String } 没有区别
  • 您是否控制台正在上传console.log(req.file) 文件?

标签: node.js mongoose multer


【解决方案1】:

好的.. 终于明白了,我在模型中使用了 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;

【讨论】:

    猜你喜欢
    • 2012-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-07
    • 2018-09-26
    • 1970-01-01
    • 1970-01-01
    • 2019-08-31
    相关资源
    最近更新 更多