Search code examples
node.jsmongodbmongoosegridfsgridfs-stream

How to remove a file from both chunks and files in GridFS?


Mongoose

var Grid = require('gridfs-stream');
var mongoose = require('mongoose');
var GridFS = Grid(mongoose.connection.db, mongoose.mongo);
GridFS.collection('backupdata').remove({_id: mongoose.Types.ObjectId(req.file_id)}, function (err) {
    console.log("deleted");
});

Here I created a collection("dbmanager") for saving files. When I try to remove file from dbmanager collection, the document will remove from "dbmanager.files". But documents still showing in "dbmanager.chunks". I need to remove that documents from "dbmanager.files" and "dbmanager.chunks".


Solution

  • I just did this recently using gridfs-stream

    Then the gfs driver does it for you:

    gfs.remove(options, function (err) {
      if (err) return handleError(err);
      console.log('success');
    });
    

    or

    gfs.remove({ _id: fileId });