【问题标题】:Gridfs delete file errorGridfs删除文件错误
【发布时间】:2017-10-03 20:27:18
【问题描述】:

我正在使用 mongoose 和 mongoose-gridfs 模块,但不知道如何修复错误。 可以轻松地将文件添加到我的数据库并读取它:

router.get('/:id', (req, res)=> {
     if (gridfs == null) {
         gridfs = require("mongoose-gridfs")({
             collection: 'attachments',
             model: 'Files'
         });
         Attachment = gridfs.model;
     }
     let stream = Attachment.readById(req.params["id"]);
}

但是当我在删除路线中使用相同的方式时:

router.delete('/:id', (req, res)=> {
     if (gridfs == null) {
         gridfs = require("mongoose-gridfs")({
             collection: 'attachments',
             model: 'Files'
         });
         Attachment = gridfs.model;
     }
     Attachment.unlinkById(req.params["id"], (err) => {
     });
}

它给我一个错误 TypeError: Cannot read property 'unlink' of null。 我做错了什么?

【问题讨论】:

    标签: node.js mongoose gridfs gridfs-stream


    【解决方案1】:

    当初始化变量 'gridfs' 并要求 'mongoose-gridfs' 尝试传入你的 mongoose 连接时,如下所示:

    //instantiate mongoose-gridfs
    var gridfs = require('mongoose-gridfs')({
      collection:'attachments',
      model:'Attachment',
      mongooseConnection: connection
    });
    

    还可能值得尝试记录 req.params["id"] 的值,以确保您在那里确实有一个 id。

    也可以尝试使用 unlink 方法代替 unlinkById,如下所示:

    Attachment.unlink(<objectid>, function(error, unlinkedAttachment){
      ...
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多