0

I'm trying to implement file upload using multer in express.js but file is not uploading in db can any one help me in this .

Here is my code:

csr.model.js

  const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const schema = new Schema({
    commonName: { type: String },
    orgName: { type: String },
    orgUnit: { type: String },
    city: { type: String },
    state: { type: String },
    country: { type: String },
    emailAdd: { type: String },
    file: { type: String },

}, { collection: 'csr' });



schema.set('toJSON', {
    virtuals: true,
    versionKey: false,
    transform: function (doc, ret) {
        delete ret._id;
        delete ret.hash;
    }
});

module.exports = mongoose.model('Csr', schema);

csr.controller.js

const express = require("express");
const router = express.Router();
const userService = require("./csr.service");
router.post("/fileupload",fileupload)

module.exports = router;

  function fileupload(req, res, next) {
    userService
  .fileupload()
  .then(() =>{
    //console.log(res);
   res.json({ success: true})})
  .catch((err) => next(err));
}

csr.service.js

 const config = require("config.json");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcryptjs");
const db = require("_helpers/db");
const crypto = require("../_helpers/crypto");
// var crypto = require("crypto");
var assert = require("assert");
var ObjectId = require("mongodb").ObjectId;
const { exec } = require("child_process");
const multer = require("multer");

const Csr = db.Csr;
module.exports = {
  fileupload
};



async function fileupload() {
    var storage = multer.diskStorage({
        destination: function(req, file, cb) {
          cb(null, "uploads/");
        },
        filename: function(req, file, cb)  {
          cb(null, `${Date.now()}_${file.originalname}`);
        },
        fileFilter: function(req, file, cb)  {
          const ext = path.extname(file.originalname);
          if (ext !== ".jpg" || ext !== ".png") {
            return cb(res.status(400).end("only jpg, png are allowed"), false);
          }
          cb(null, true);
        },
      });
    
      var upload = multer({ storage: storage }).single("file");
      var csr = new Csr();
      await csr.save();
      console.log(upload)
      return upload
  }

Please suggest what is wrong in this code when I return console.log(upload) in console I got this [Function: multerMiddleware] and console.log(storage) returning like this DiskStorage { getFilename: [Function: filename], getDestination: [Function: destination] } Please some one suggest me the solution.

Thank you

sss
  • 251
  • 5
  • 18
  • why not just return "multer({ storage: storage })" and use it like : route.post('/something', upload.single('avatar'), async (req, res, next) => {}) ? And why are you trying to save files to database anyway? it can harm performance – Me Bottle O Scrumpy Apr 07 '21 at 15:29
  • Can you please explain how I need to change in my code – sss Apr 07 '21 at 15:30
  • I need to store fie in db that is the requirement – sss Apr 07 '21 at 15:40
  • this question is similar to this https://stackoverflow.com/questions/14017826/storing-a-file-in-mongodb-using-node-js. maybe you can find your answer there – Me Bottle O Scrumpy Apr 07 '21 at 15:44

0 Answers0