Failling to read properties of the file after saving it in mongoDb

31 views Asked by At

am trying to save a text file to a mongoDB using gridfs. I am able to save the file in the database but after that, the the application stops and returns cannot read property of undefined i.e reading _id. Am using node v18.17.1. I can't seem to figure out what the problem is.

const express = require("express");
const multer = require("multer");
const { GridFsStorage } = require("multer-gridfs-storage");
const mongoose = require("mongoose");
const { GridFSBucket } = require("mongodb");
require("dotenv").config();

const url = process.env.MONGO_DB_URL;
mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true });
const conn = mongoose.connection;
let gfs;

conn.once("open", () => {
  gfs = new GridFSBucket(conn.db, {
    bucketName: "fileUploads",
  });
});

const storage = new GridFsStorage({
  url,
  file: (req, file) => {
    return {
      bucketName: "fileUploads",
      filename: `${Date.now()}_${file.originalname}`,
    };
  },
});

const upload = multer({ storage });

const app = express();

app.post("/upload/document", upload.single("doc"), (req, res) => {
  try {
    const file = req.file;

    if (file) {
      console.log(file);
      res.send({
        message: "File uploaded successfully!!",
        id: file.id,
        name: file.filename,
        contentType: file.contentType,
      });
    } else {
      res.status(400).send("No file uploaded");
    }
  } catch (err) {
    console.log("Error: ", err);
  }
});

const server = app.listen(process.env.PORT || 8765, function () {
  const port = server.address().port;
  console.log("App started at port:", port);
});

I expect it to return the file details upon the successful uploading of the file as show above.

0

There are 0 answers