Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gfs is undefined #15

Open
SUMANTH-hyphen opened this issue May 30, 2023 · 0 comments
Open

gfs is undefined #15

SUMANTH-hyphen opened this issue May 30, 2023 · 0 comments

Comments

@SUMANTH-hyphen
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant