3

Building a REST API with FeathersJS I need to be able to upload a picture (POST), record if thanks to GridFS and be able GET it later.

I start set up GridFS with Mongoose:

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);
};

Then add in my /pub service :

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);
      }
    ],

And then I get an error saying :

MongoError: file with id ### not opened for writing

Where ### is the filename instead of the _id

Ragnar
  • 2,550
  • 6
  • 36
  • 70

0 Answers0