在NodeJS中使用gridfs通过元数据删除文件

Deleting file by metadata with gridfs in NodeJS

本文关键字:元数据 删除 文件 gridfs NodeJS      更新时间:2023-09-26

我正在尝试使用gridfs删除mongodb数据库中的文件。我想删除所有包含元数据的文件。关系= id。以下是我在NodeJS中的方法:

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

错误是:

C: ' ' Gaute '用户文档' GitHub ' WikiHelpSystem ' node_modules '猫鼬' node_module年代' mongodb ' lib ' mongodb ' gridfs ' gridstore.js: 1138
如果名字。构造函数==数组){

     ^

TypeError: Cannot read property 'constructor' of undefinedC:'Users'Gaute'Documents'GitHub'WikiHelpSystem' node_modules '猫鼬' node_modules ' mongodb ' lib ' mongodb ' gridfs ' gridstore.js: 1138: 11)

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

您需要首先获得id,使用MongoDb驱动程序。

// 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;          
    })
});
 gfs.files.remove({_id:_id} , function(err){
                                            if (err){
                                                 console.log("error");
                                            }else{
                                              console.log("old file removed")
                                            }           
                                   });