如何将gridfs与猫鼬模式相关联?

时间:2019-08-08 13:20:03

标签: mongodb mongoose gridfs

我的规范架构应该有两个字段,一个是名称字段,另一个是图像文件。为此,我写了一个这样的文件:

'use strict'

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const multer = require('multer');
const Grid = require('gridfs-stream');
const GridFsStorage = require('multer-gridfs-storage');
const URI = require('../config/configuration');

mongoose.connect(URI, { useNewUrlParser: true })
const conn = mongoose.connection;
console.log("conn: ",conn)
// conenct Grid and mongo
Grid.mongo = mongoose.mongo;
  // make sure the db instance is open before passing into `Grid`
conn.once('open', function() {
    //initialize gridfs stream
    let gfs = Grid(conn.db, mongoose.mongo);
    gfs.collection('avatarImage');
})
    // Create storage engine
const storage = new GridFsStorage({
      url: URI,
      file: (req, file) => {
        console.log('file req: ', req.body.avatarName);
        console.log('file file: ', file);

        return new Promise((resolve, reject) => {
          if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
            const id = req.query.id;
            const avatarName = `${id}_${req.query.avatarName}`;

            const filename = {
              originalName: file.originalname,
              avatarId: id,
              avatarName: avatarName.toLowerCase().replace(/\s/g, '')
            };
            const fileInfo = {
              filename,
              bucketName: 'avatarImage'
            };
            resolve(fileInfo);
          } else {
            throw TypeError('file type is unknown');
          }
        });
      }
    });



const upload = multer({ storage }).single('file');


 const specificationModelSchema = new Schema({
    name: {
        type:String
         } ,
    image :{
         type:Schema.Types.SchemaId,
         ref: 'GFS'
        }

});

const GFSSchema = new Schema ({}, 'fs.files');
const GFSModel = mongoose.model('GFS', GFSSchema);
const SpecificationSchama = mongoose.model ('SpecificationSchama', specificationModelSchema)
module.exports = {SpecificationSchama, upload} 

但是我遇到此错误:

TypeError: Invalid value for schema path `image.type`, got value "undefined"

我在这里有点困惑。我不知道如何将我的图像ID与我的SpecificationSchama关联。

可能的解决方案是什么?我很高兴您的宝贵建议。

0 个答案:

没有答案