0
var GridFS = Grid(mongoose.connection.db, mongoose.mongo);
GridFS.remove({_id: mongoose.Types.ObjectId(req.params.file_id)}, function (err) {
    if (!err) {
        return res.send(204);
    } else {
        console.log("error");
    }
});

using above code I can delete documents from fs.files collections. But its not romoving from fs.chunks collections. How I can delete documents from both collections fs.files and fs.chunks.

Naveen
  • 757
  • 3
  • 17
  • 41

1 Answers1

0

gridfs-stream module take care of removing boths files and chunks with the help of the native GridStore unlink method.
http://mongodb.github.io/node-mongodb-native/api-generated/gridstore.html#gridstore-unlink.

You can check the module source code if you want to be absolutly clear about that.

I think your problem here is you try to pass some extra Mongoose schema type (mongoose.Types.ObjectId) while you do not need that at all.

Just pass the file _id (or filename) to your GridFS remove function like this:

GridFS.remove({ _id: req.params.file_id }, (err) => {
    if (err) console.log(err)
    res.sendStatus(204)
})

Also make sure to do not make the same mistake I made today, using the Mongoose remove method from your custom file Schema. Logically, it will delete the file but not the chunk as I realized some time after.

TGrif
  • 5,725
  • 9
  • 31
  • 52
  • Can I do that based on an array? Delete files (chunks too) where ids are in array, ex: `.remove({ _id: { $in: filesIdsToDelete } },...` – Mathiasfc Jan 11 '19 at 13:27
  • @MathiasFalci Not sure (not tested), you'll have to try it. If it doesn't, you can always loop on your array. – TGrif Jan 11 '19 at 13:36
  • Thank's, I will try... But now, I'm trying simple passing the file id and the `.remove` method deletes only files documents in db, not chunks :/ – Mathiasfc Jan 11 '19 at 15:02