Question

I am trying to delete files in my mongodb database using gridfs. I want to delete all the files with the metadata.relation = id. Here is my method in NodeJS:

function deleteFiles(){
    gfs.remove({'metadata.relation': req.body._id }, function(err){
      if (err) return false;
      return true;          
    })
}

The error is:

C:\Users\Gaute\Documents\GitHub\WikiHelpSystem\node_modules\mongoose\node_module s\mongodb\lib\mongodb\gridfs\gridstore.js:1138
if(names.constructor == Array) {

     ^

TypeError: Cannot read property 'constructor' of undefined at Function.GridStore.unlink (C:\Users\Gaute\Documents\GitHub\WikiHelpSystem \node_modules\mongoose\node_modules\mongodb\lib\mongodb\gridfs\gridstore.js:1138 :11)

Was it helpful?

Solution

Assuming you are using gridfs-stream module, then when you call gfs.remove with an object, it will expect that the object will contain an _id.

You need to first get the id, using MongoDb driver.

// This should be your files metadata collection, fs.files is the default collection for it. 
var collection = db.collection('fs.files');     
collection.findOne({'metadata.relation': req.body._id }, { _id : 1 }, function (err, obj) {
    if (err) return cb(err); // don't forget to handle error/
    gfs.remove(obj, function(err){
      if (err) return false;
      return true;          
    })
});

OTHER TIPS

 gfs.files.remove({_id:_id} , function(err){
                                            if (err){
                                                 console.log("error");
                                            }else{
                                              console.log("old file removed")
                                            }           
                                   }); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top