Home > OS >  unable to upload files to mongodb with GridFsStorage
unable to upload files to mongodb with GridFsStorage

Time:04-21

database connection file

const mongoose = require('mongoose');
const multer = require('multer')
const {GridFsStorage} = require('multer-gridfs-storage')
const Grid = require('gridfs-stream');
const path = require('path');
const dotenv = require('dotenv');
const crypto = require('crypto')
dotenv.config( { path : 'config.env'} )
let storage;
exports.connectDB = ()=>{
    try{
        const con = mongoose.createConnection(process.env.MONGO_URL,{
            useNewUrlParser:true,
            useUnifiedTopology:true,

        })
        con.once('open', () => {
            // Init stream
           const gfs = Grid(con.db, mongoose.mongo);
            gfs.collection('uploads');
          });
        console.log(`MongoDB connected:${con}`)
    }catch(err){
        console.log(err);
        process.exit(1);
    }
} 

exports.createStorage = ()=>{
    storage = new GridFsStorage({
        url: process.env.MONGO_URL,
        file: (req, file) => {
          return new Promise((resolve, reject) => {
            crypto.randomBytes(16, (err, buf) => {
              if (err) {
                return reject(err);
              }
              const filename = buf.toString('hex')   path.extname(file.originalname);
              const fileInfo = {
                filename: filename,
                bucketName: 'uploads'
              };
              resolve(fileInfo);
            });
          });
        }
      });
      console.log('storage created')
}
exports.upload = multer({storage})

post request with upload as middleware

route.post('/example',database.upload.single('file'),async (req,res)=>{
    res.json({file:req.file})
})

when I do a post request with postman there's no error but file doesn't upload on MongoDB neither the upload collection is being created.

I am calling the connectDB and createStorage from index.js

database.connectDB();
database.createStorage();

CodePudding user response:

I resolved it. the problem was

exports.upload = multer({storage})

this line of code was executed before calling of

database.createStorage();

so the the solution is

exports.createStorage = ()=>{
  storage = new GridFsStorage({
    url:process.env.MONGO_URL,
    // db:conn.connection.db,
    file: (req, file) => {
      return new Promise((resolve, reject) => {
        crypto.randomBytes(16, (err, buf) => {
          if (err) {
            return reject(err);
          }
          const filename = buf.toString('hex')   path.extname(file.originalname);
          const fileInfo = {
            filename: filename,
            bucketName: 'uploads'
          };
          resolve(fileInfo);
        });
      });
    }
  });
  exports.upload = multer({storage})
}
  • Related