Error with the _id property in GridFS storage in mongoDB while uploading files

168 views Asked by At

I was tring to build a social app where users can post articles with images, to store these data I am using mongoDB with gridFS for storing images. I am using multer-gridfs-storage to use as a middleware to handle files. But whenever I am trying to upload a file, the server crashes showing that the _id property in the gridfs.js file is undefined. I have tried every options to resolve the issue but still it is unsolved

This is my upload.js middleware

const multer = require("multer");
const { GridFsStorage } = require("multer-gridfs-storage");
const MongoClient = require("mongodb").MongoClient;
require("dotenv").config();
// const methodOverride = require("method-override");

const promise = MongoClient.connect(process.env.MONGO_URI).then((client) =>
  client.db(process.env.DATABASE)
);

const storage = new GridFsStorage({
  // url: process.env.MONGO_URI,
  db: promise,
  options: { useNewUrlParser: true, useUnifiedTopology: true },
  file: (req, file) => {
    console.log(file);
    const match = ["image/png", "image/jpeg", "image/jpg"];
    // console.log(file);
    if (match.indexOf(file.mimetype) === -1) {
      return {
        bucketName: "files",
        filename: `${Date.now()}-posts-${file.originalname}`
      };
    }

    return {
      bucketName: "photos",
      filename: `${Date.now()}-posts-${file.originalname}`
    };

  }
});

// const upload = multer({ storage });

// module.exports = upload;
module.exports = multer({ storage }).fields([
  { name: "image", maxCount: 1 },
  // { name: "coverLetter", maxCount: 1 },
]);

and this is the error

                        id: f._id,
                              ^

TypeError: Cannot read properties of undefined (reading '_id')
    at GridFSBucketWriteStream.emitFile (C:\Users\ariel\OneDrive\Desktop\react-native\project2\server\apis\node_modules\multer-gridfs-storage\lib\gridfs.js:306:31)
    at GridFSBucketWriteStream.emit (node:events:525:35)
    at finish (node:internal/streams/writable:748:10)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21)

I tried changine the configurations of my mongoDB connections along with looking into the GridFs.js file for the issue but, didn't reach a solution.

1

There are 1 answers

0
Stha Sandes On

I had the same problem. Somehow connect-mongo was making this happen so I just installed version 3.2.0 of connect-mongo which solved the problem.