使用NodeJS中的gridfs按元数据删除文件

use*_*894 3 javascript mongodb node.js gridfs

我试图使用gridfs删除我的mongodb数据库中的文件.我想删除所有带有metadata.relation = id的文件.这是我在NodeJS中的方法:

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

错误是:

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

     ^
Run Code Online (Sandbox Code Playgroud)

TypeError:无法在Function.GridStore.unlink中读取未定义的属性'constructor'(C:\ Users\Gaute\Documents\GitHub\WikiHelpSystem \node_modules\mongoose \node_modules\mongodb\lib\mongodb\gridfs\gridstore.js:1138: 11)

Far*_*hat 6

假设您正在使用gridfs-stream模块,那么当您gfs.remove使用对象调用时,它将期望该对象将包含一个_id.

你需要先使用MongoDb驱动程序获取id.

// 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;          
    })
});
Run Code Online (Sandbox Code Playgroud)