使用FeathersJs存储带有Mongoose / GridFS的文件

时间:2017-08-14 21:57:46

标签: node.js mongodb gridfs feathersjs gridfs-stream

使用FeathersJS构建REST API我需要能够上传图片(POST),如果感谢GridFS就能记录下来并且能够在以后获取它。

我开始使用Mongoose设置GridFS:

const mongoose = require('mongoose');
const Grid = require('gridfs-stream');
Grid.mongo = mongoose.mongo;

module.exports = function () {
  const app = this;

  mongoose.connect(app.get('mongodb'));
  const cnx = mongoose.connection;
  mongoose.Promise = global.Promise;

  cnx.once('open', () => {
    const gfs = Grid(cnx.db);
    app.set('gfs', gfs);
  })

  app.set('mongooseClient', mongoose);
};

然后添加我的/pub服务:

  

pub.service.js

const multipartMiddleware = require('multer')();
[...]
app.use('/pub', 
      multipartMiddleware.single('uri'),
      function(req, res, next){
        req.feathers.file = req.file;
        next();
      },
      createService(options)
    );
  

pub.hook.js

create: [
      hook => {
        const gfs = hook.app.get('gfs');
        const file = hook.params.file;

        console.log(hook)

        const writestream = gfs.createReadStream({
          filename: file.originalname,
          content_type: file.mimetype, // image/jpeg or image/png
        })
        const dir = __dirname;
        fs.createReadStream(`${__dirname}/img`).pipe(writestream);
      }
    ],

然后我收到错误说:

  

MongoError:id为###的文件未打开以进行编写

其中###是文件名而不是_id

0 个答案:

没有答案