javascript - 在 NodeJS 中使用 gridfs 按元数据删除文件

标签 javascript node.js mongodb gridfs

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

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

错误是:

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)

最佳答案

假设您使用的是 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;          
    })
});

关于javascript - 在 NodeJS 中使用 gridfs 按元数据删除文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23514671/

相关文章:

python - Mongodb FindAndModify 多进程使用问题

javascript - 如果未在字段中输入任何内容,如何才能使结果返回 '0' 而不是 NaN。

javascript - 回调函数——javascript

javascript - 当草稿编辑器处于只读模式时 onChange 不会触发

node.js - 如何从松弛自定义命令中获取变量到参数中

php - MongoDB:复合索引决策

javascript - 简单的 JavaScript 运行在客户端还是服务器端?

javascript - vuejs - 如何将自定义图标添加到 Quill(撤消/重做)

node.js - 类型错误 : Cannot read property 'save' of null

javascript - 在 MongoDB 中使用 $lt 和 $gt 过滤日期值