0

I'm using mongoose and mongoose-gridfs module and can't figure out how to fix error. Can easily add file to my db and read it:

router.get('/:id', (req, res)=> {
     if (gridfs == null) {
         gridfs = require("mongoose-gridfs")({
             collection: 'attachments',
             model: 'Files'
         });
         Attachment = gridfs.model;
     }
     let stream = Attachment.readById(req.params["id"]);
}

But when i'm using the same way in delete route:

router.delete('/:id', (req, res)=> {
     if (gridfs == null) {
         gridfs = require("mongoose-gridfs")({
             collection: 'attachments',
             model: 'Files'
         });
         Attachment = gridfs.model;
     }
     Attachment.unlinkById(req.params["id"], (err) => {
     });
}

It's throw me an error TypeError: Cannot read property 'unlink' of null. What am i doing wrong?

Mongoname
  • 65
  • 9

1 Answers1

0

When initializing the variable 'gridfs' and requiring 'mongoose-gridfs' try passing in your mongoose connection as shown below:

//instantiate mongoose-gridfs
var gridfs = require('mongoose-gridfs')({
  collection:'attachments',
  model:'Attachment',
  mongooseConnection: connection
});

It might also be worth trying to log the value of req.params["id"] to ensure you do have an id there.

Also try the unlink method instead of unlinkById as shown below:

Attachment.unlink(<objectid>, function(error, unlinkedAttachment){
  ...
});