Reputation: 23
I've got this JS code for my Next.js API. I'm trying to store images in MongoDB GridFS and retrieve them with a simple API route. The code you are seeing is from a file that gets imported in 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)
grid.collection("fs.files")
return {
client,
db: db,
gfs: grid
}
})
}
cached.conn = await cached.promise
return cached.conn
}
When I try to use createReadStream
I get the following error:
TypeError: grid.mongo.ObjectID is not a constructor
The issue is with const grid = Grid(db, MongoClient)
but I have no idea how to fix it. Any help would be greatly appreciated.
Edit: Fixed the issue. I wasn't meant to use grid.collection
.
Upvotes: 0
Views: 1179
Reputation: 1
grid fs stream is depreciated and not needed with newer versions of mongoDB. use GridFSBucket instead.
Upvotes: 0