You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在MVC项目中使用GridFS时,为何gfs.find()提示不是函数?

问题:GridFSBucket调用find()报错TypeError: gfs.find is not a function

我正在将一套文件上传代码拆分整合到自己的MVC架构网站中,适配现有MongoDB + Mongoose的实现,原代码运行正常。

数据库连接代码

我调整后的数据库连接函数如下:

const connectDB = async () => {
  try {
    const conn = mongoose.connection;
    // 监听连接错误
    conn.on("error", (err) => {
      console.error(`connection error: ${err.message}`);
    });
    conn.once("open", () => {
      console.log("MongoDB Connected");
    });

    // 初始化GridFSBucket
    let gfs;
    conn.once("open", () => {
      gfs = new mongoose.mongo.GridFSBucket(mongoose.connection.db, {
        bucketName: "assets",
      });
    });

    // 建立连接
    await mongoose.connect(process.env.MONGO_URI);

    return gfs;
  } catch (err) {
    console.error(err.message);
    process.exit(1);
  }
};

我了解mongoose.connect()是单例模式,多次调用不会创建多个连接,所以直接在控制器中调用这个函数获取bucket,用来执行find()查询数据,但目前遇到了问题。

控制器代码

我的控制器代码如下:

const gfs = require("../config/db").connectDB();

const uploadFile = (req, res) => {
  return res.json({
    message: "File uploaded successfully: " + req.file.filename,
  });
};

const getMyFilenames = async (req, res) => {
  console.log(gfs);
  try {
    const files = await gfs
      .find({
        //"metadata.uploader": req.user._id
      })
      .toArray();
    if (!files || files.length === 0) {
      return res.status(404).json({
        message: "No files available",
      });
    }
    const filenames = files.map((file) => file.filename.split("-")[1]);
    console.log(filenames);
    return res.json(filenames);
  } catch (err) {
    console.error(err);
  }
};

问题详情

控制台打印gfs的结果是一个包裹着GridFSBucket对象的Promise:

[0] Promise {
[0]   GridFSBucket {
[0]     _events: [Object: null prototype] {},
[0]     _eventsCount: 0,
[0]     _maxListeners: 0,
[0]     s: {
[0]       db: [Db],
[0]       options: [Object],
[0]       _chunksCollection: [Collection],
[0]       _filesCollection: [Collection],
[0]       checkedIndexes: false,
[0]       calledOpenUploadStream: false
[0]     },
[0]     [Symbol(kCapture)]: false
[0]   }
[0] }

但调用gfs.find()时,抛出错误:

TypeError: gfs.find is not a function

希望得到解决这个报错的建议,同时想了解有没有更优的GridFSBucket初始化和使用方案。


内容的提问来源于stack exchange,提问作者user17433353

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 23:05:27