I have been working on implementing a JS code for my Next.js API that involves storing images in MongoDB GridFS and retrieving them via a simple API route. The snippet you see is from a file that is imported into the API route.
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)
// Removed grid.collection("fs.files") as it caused an error
return {
client,
db: db,
gfs: grid
}
})
}
cached.conn = await cached.promise
return cached.conn
}
While attempting to use createReadStream
, I encountered the following error:
TypeError: grid.mongo.ObjectID is not a constructor
The problem seems to be related to
const grid = Grid(db, MongoClient)
but unfortunately, I'm unsure about how to resolve it. Any assistance on this matter would be highly appreciated.
Edit: Resolved the issue by removing grid.collection
.