类型错误:grid.mongo.ObjectID 不是构造函数

问题描述

我有我的 Next.js API 的这个 JS 代码。我正在尝试将图像存储在 MongoDB GridFS 中并使用简单的 API 路由检索它们。您看到的代码来自在 API 路由中导入的文件

import { MongoClient } from "mongodb"
import Grid from "gridfs-stream"

const { MONGODB_URI,MONGODB_DB } = process.env

if (!MONGODB_URI) {
  throw new Error(
    "Please define the MONGODB_URI environment variable inside .env.local"
  )
}

if (!MONGODB_DB) {
  throw new Error(
    "Please define the MONGODB_DB environment variable inside .env.local"
  )
}

let cached = global.mongo

if (!cached) {
  cached = global.mongo = { conn: null,promise: null }
}

export async function connectToDatabase(dbIndex = 0) {
  if (cached.conn) {
    return cached.conn
  }

  if (!cached.promise) {
    const opts = {
      useNewUrlParser: true,useUnifiedTopology: true
    }

    cached.promise = MongoClient.connect(MONGODB_URI,opts).then((client) => {
      const db = client.db(MONGODB_DB.split(",")[dbIndex])
      const grid = Grid(db,MongoClient)
      grid.collection("fs.files")
      return {
        client,db: db,gfs: grid
      }
    })
  }
  cached.conn = await cached.promise
  return cached.conn
}

当我尝试使用 createReadStream 时,出现以下错误

TypeError: grid.mongo.ObjectID is not a constructor

问题出在 const grid = Grid(db,MongoClient) 上,但我不知道如何解决。任何帮助将不胜感激。

编辑:修复了问题。我不打算使用 grid.collection

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)