【问题标题】:Posting two collections at once with multer使用 multer 一次发布两个集合
【发布时间】:2020-03-24 13:59:28
【问题描述】:

我在发布两个集合时遇到问题 - 一个是文件,一个是基于文件的字段的文字对象。 这是路由方法

// @route POST /upload
// @desc  Uploads file to DB
router.post('/', upload.single('file'), auth, (req, res) => {
  const newFile = new File({
    fileID: req.file.id,
    src: 'api/files/image/' + req.file.filename,
    altText: 'No image',
    caption: req.body.caption
  })
  newFile.save()

});

和文件模型:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Create Schema
const FileSchema = new Schema({
  fileID: {
    type: Schema.Types.ObjectId
  },
  src: {
    type: String
  },
  altText: {
    type: String
  },
  caption: {
    type: String
  }
});

module.exports = File = mongoose.model('file', FileSchema);

问题是,如果我这样做,我将无法获得标题属性并且我有错误:

TypeError: 无法读取未定义的属性“id”

或者如果我删除它

req.file.id

我明白了

TypeError: 无法读取未定义的属性“文件名”

即使我在我的数据库中获得了良好的价值。 如果我同时删除 id 和文件名,我会得到标题属性。 所以问题就在这里:

    fileID: req.file.id,
    src: 'api/files/image/' + req.file.filename

但我不知道如何处理。

【问题讨论】:

    标签: javascript post multer gridfs


    【解决方案1】:

    我仍然不知道如何处理它,但我在post route方法中做了控制台登录: // @route POST /上传 // @desc 上传文件到数据库

    router.post('/', upload.single('file'), auth, (req, res) => {
    console.log(req.file);
      const newFile = new File({
        fileID: req.file.id,
        src: 'api/files/image/' + req.file.filename,
        altText: 'No image',
        caption: req.body.caption
      })
      newFile.save()
    
    });
    

    我得到:

    undefined
    [0] { fieldname: 'file',
    [0]   originalname: 'slide1.jpg',
    [0]   encoding: '7bit',
    [0]   mimetype: 'image/jpeg',
    [0]   id: 5de06f65ff1bdb5388f1a44c,
    [0]   filename: 'e872d1cafee8d191b256d27efc5ac94f.jpg',
    [0]   metadata: null,
    [0]   bucketName: 'files',
    [0]   chunkSize: 261120,
    [0]   size: 235600,
    [0]   md5: '06ef6fba95a331af99276199589d3ed4',
    [0]   uploadDate: 2019-11-29T01:07:50.105Z,
    [0]   contentType: 'image/jpeg' }
    

    所以看起来我必须等待请求,因为

    请求文件

    尚未定义,所以我收到错误,它停止并且不发布此 req.body.caption。 这就是我的怀疑。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-06
      • 1970-01-01
      • 1970-01-01
      • 2017-01-30
      • 1970-01-01
      • 1970-01-01
      • 2015-03-12
      相关资源
      最近更新 更多