#Get access to class variable in another file

3 messages · Page 1 of 1 (latest)

dreamy chasm
#

Hi, I'm trying to get access to "gfs" variable from MyGridFS class in controller file but whatever I'm trying I'm getting undefined error and I'm run out of ideas how can I salve this.(Controller file also is based on class.)

class MyGridFS {
  constructor() {
    let gfs = this.gfs;
    let gridfsBucket = this.gridfsBucket;
  }
  initializeGridFS(conn) {
    this.conn = conn;
    conn.once("open", () => {
      this.gridfsBucket = new mongoose.mongo.GridFSBucket(conn.db, {
        bucketName: "uploads",
      });
      this.gfs = Grid(conn.db, mongoose.mongo);
      this.gfs.collection("uploads");
    });
  }
  initializeStorage(mongo_uri) {
    this.mongo_uri = mongo_uri;
    const storage = new GridFsStorage({
      url: this.mongo_uri,
      file: (req, file) => {
        const filename = "file_" + Date.now() + path.extname(file.originalname);
        return {
          filename,
          bucketName: "uploads",
        };
      },
    });
    this.upload = multer({ storage });
  }
}
placid moss
dreamy chasm
# placid moss What are you trying and what error are you getting?

For example when I try extends controller class with MtGridFS class and try to use "" I'm getting "TypeError: Cannot read properties of undefined (reading 'files')". Also if I'm trying to fetch one image I'm getting error code 500 in postman and same error in vscode

class UploadController extends MyGridFS {
  constructor() {
    super();
  }
  async getAllPhotos(req, res) {
    try {
      const files = await this.gfs.files.find({}).toArray();

      if (files) {
        files.map((file) => {
          if (
            file.contentType === "image/jpeg" ||
            file.contentType === "image/png"
          ) {
            file.isImage = true;
          } else {
            file.isImage = false;
          }
        });
        //res.render("index", { files: files });
        res.json({ files });
      }
    } catch (error) {
      console.log(error);
    }
  }
}