aheckmann / gridfs-stream

Easily stream files to and from MongoDB
MIT License
615 stars 120 forks source link

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

Open gfelot opened 7 years ago

gfelot commented 7 years ago

Need to store picture with my API using FeatherJS.

I got the error MongoError: file with id ### not opened for writing.

with ### is the name of the current file. Do I have to set up manually the ObjectId of the metadata written inside mongo ?

my code for my /pub service (if you are familiar with feathersJS):

pub.service.js

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

What did I miss ?

Chronicless commented 7 years ago

the same issue . Did you solve it?

healiha commented 7 years ago

As you want to write to GridFS, you should use Grid.createWriteStream instead of Grid.createReadStream. Then, using fs to read the content of your file fs.createReadStream(filePath).pipe(writestream) to actually write the content of the file to GridFS.

pub.hook.js


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

    const writestream = gfs.createWriteStream({
      filename: file.originalname,
      content_type: file.mimetype, // image/jpeg or image/png
    });
    fs.createReadStream(filePath).pipe(writestream);
  }
],

...