编程语言
首页 > 编程语言> > javascript – 在NodeJS中使用gridfs按元数据删除文件

javascript – 在NodeJS中使用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) {

06001

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;          
    })
});

标签:gridfs,javascript,mongodb,node-js
来源: https://codeday.me/bug/20190825/1715548.html