gridfs-file-storage
gridfs-file-storage copied to clipboard
gfs is undefined
I'm trying to connect to the database and declare the gfs variable in one file and share it to another file where I want to fetch the file details
mongo.connection.js
const mongoose = require("mongoose");
const Grid = require("gridfs-stream");
let gfs;
const establishConnection = async () => {
try {
mongoose.set("strictQuery", false);
await mongoose.connect(process.env.DB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const connect = mongoose.connection;
connect.on("error", (err) => {
console.error("Mongoose connection error:", err);
});
connect.once("open", () => {
gfs = new mongoose.mongo.GridFSBucket(connect.db, { bucketName: "uploads" });
console.log("Mongoose connection successful.");
});
} catch (err) {
console.error("Mongoose connection error:", err);
throw err;
}
};
const getGfsInstance = () => {
if (!gfs) {
throw new Error("Connection not established. Call establishConnection first.");
}
return gfs;
};
module.exports = { establishConnection, getGfsInstance };
user.controller.js
const { gfs } = require("../connnection/mongo.connection");
exports.postRetriveAll = async (res, req) => {
try {
// await establishConnection();
console.log("Retrieved gfs:", gfs);
// Retrieve all file details from the "uploads" bucket
gfs.find({}).toArray((err, files) => {
if (err) {
console.error("Error:", err);
} else {
console.log("Files:", files);
}
});
}
catch (err) {
console.log(err);
return err;
}
};
Output
Mongoose connection successful.
Retrieved gfs: undefined
TypeError: Cannot read properties of undefined (reading 'find')
i have called establishConnection() function in app.js file initially and also called it once again in user.controller.js but it didn't worked i also used the promise method but it didn't work