aheckmann / gridfs-stream

Easily stream files to and from MongoDB
MIT License
615 stars 120 forks source link

TypeError: grid.mongo.ObjectID is not a constructor #156

Open zxcvpn011 opened 1 year ago

zxcvpn011 commented 1 year ago

whenever I try to use gfs.createReadStream I keep getting this error

...\node_modules\gridfs-stream\lib\readstream.js:68
  this._store = new grid.mongo.GridStore(grid.db, this.id || new grid.mongo.ObjectID(), this.name, this.mode, options);
                                                             ^

TypeError: grid.mongo.ObjectID is not a constructor

I don't know where's the mistake I made I tried to search everywhere but I'm not found any solution here's my code

const express = require('express');
const router = express.Router();
const multer = require("multer");
const { GridFsStorage } = require('multer-gridfs-storage');
const { connection } = require('../db/connection');
const createError = require('http-errors');
const mongoose = require("mongoose")
const Grid = require("gridfs-stream")
const gfsStorage = new GridFsStorage({ 
  db: connection,
  file: (req, file) => {
    let extname = path.extname(file.originalname);
    //handle the file name changes
    const originalname = Buffer.from(file.originalname, "latin1").toString("utf8");
    return {
      filename: `${generateRandomId()}--${originalname}`
    };
  },
});
const gfsUpload = multer({ storage: gfsStorage });
const gfs = Grid(connection, mongoose.mongo);
 gfs.collection('fs')

router.post("/gridfs", gfsUpload.single("file"), function (req, res, next) {
  let { filename, chunkSize, id } = req.file;
  console.log(req.file)
  res.status(200).json({
    file: { filename, id }
  });
})

router.get("/gridfs/:filename", async function (req, res, next) {
  const gfsFiles = connection.collection("fs.files");

  console.log(req.params.filename);

  const file = await gfsFiles.findOne({ filename: req.params.filename });

  if(!file) return next(createError(404));

  res.setHeader("Content-Disposition", `attachment; filename=${file.filename}`);
  res.setHeader("Content-Type", file.contentType);

  gfs.createReadStream({ filename: file.filename }).pipe(res)
})

if you are asking what's inside the '../db/connection' here's the code

const mongoose = require("mongoose");
const { mongoURI } = require("../configurations/appConfig")

mongoose.set('strictQuery', true);
mongoose.connect(mongoURI, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});
const connection = mongoose.connection;

connection.on("error", (e) => {
  console.error(e);
});

connection.once("open", () => {
  console.log("connected to db");
});

exports.connection = connection

I hope to found a solution for that

Usmanali3323 commented 10 months ago

i'm facing same issue did you find out what is issue with that?