0

I have try to insert some data into mongodb database using node js REST API but I got an error Unexpected field Im new to node please help me. whitePaper is my pdf file If I upload data like title, description and image only it gives the Correct answer with status code 201 but I try to upload all data and pdf but it gives the error

model code:

    description: {
      type: String,
      required: true
    },
    imgURL: {
      type: String,
      required: true
   },
   whitePaperLink: {
      type: String,
      required: true,
                
   },

app.js file

app.use('/whitePaper', express.static('whitePaper'));

router file

const whitePaperLink = multer.diskStorage({
 destination: './whitePaper/',
 filename: (req, file, cb) => {
      return cb(null, `${file.fieldname}_${Date.now()}${path.extname(file.originalname)}`);
 }
});
const whitePaperFilter = (req, file, cb) => {
 if (file.mimetype === 'application/pdf') {
      cb(null, true)
 } else {
      cb(null, false)
 }
};
const whitePaperUpload = multer({
 storage: whitePaperLink,
 limits: {
      fileSize: 1024 * 1024 * 5
 },
 fileFilter: whitePaperFilter
 });

router.post('/', checkAuth, imageUpload.single('imgURL'), whitePaperUpload.single('whitePaperLink'), 
PostController.create_Post)

controller file

exports.create_Post = async (req, res) => {
 const post = new Post({
      title: req.body.title,
      category: req.body.category,
      description: req.body.description,
      imgURL: req.file.path,
      whitePaperLink: req.file.path,
      publishDate: req.body.publishDate,
 });

 try {
      const addPost = await post.save()
      res.status(201).json({
           message: 'Post Added Succesfully.'
      })
 } catch (error) {
      console.log(error);
      res.status(500).json({
           message: error
      })

 }
}
2
  • You've shared the code but please mention what is the error you are facing. Commented Jun 3, 2021 at 13:16
  • @Abhishek I have got error is Unexpected field for whitePaperLink Commented Jun 3, 2021 at 14:00

1 Answer 1

1

If you'll use upload.single for each field it'll give error Unexpected Field.

Multer takes all files at once for execution, and in your case you've 2 different files and it'll take both files to upload.single.

So, instead of upload.single use upload.fields.

In your route.js, do it like this:

const destination = (req, file, cb) => {
     switch (file.mimetype) {
          case 'image/jpeg':
               cb(null, './images/');
               break;
          case 'image/png':
               cb(null, './images/');
               break;
          case 'application/pdf':
               cb(null, './whitePaper/');
               break;
          default:
               cb('invalid file');
               break;
     }
}

const storage = multer.diskStorage({
     destination: destination,
     filename: (req, file, cb) => {
          return cb(null, `${file.fieldname}_${Date.now()}${path.extname(file.originalname)}`);
     }
});

const fileFilter = (req, file, cb) => {
     if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png' || file.mimetype === 'application/pdf') {
          cb(null, true)
     } else {
          cb(null, false)
     }
};

const upload = multer({
     storage: storage,
     limits: {
          fileSize: 1024 * 1024 * 5,
     },
     fileFilter: fileFilter
});

// add post
router.post('/', upload.fields([{ name: 'imgURL', maxCount: 1 }, { name: 'whitePaperLink', maxCount: 1 }]), PostController.create_Post)

Edit:

You can also do it like this:

const uploadPostData = (req, res, next) => {
     upload.fields([{ name: 'imgURL', maxCount: 1 }, { name: 'whitePaperLink', maxCount: 1 }])(req, res, (err) => {
          console.log(req.files);
          req.body.imgURL = req.files.imgURL[0].path.replace('/\\/g','/');
          req.body.whitePaperLink = req.files.whitePaperLink[0].path.replace('/\\/g','/');
          next()
     })
}

// add post
router.post('/', uploadPostData, PostController.create_Post)

Sign up to request clarification or add additional context in comments.

8 Comments

Sir I have try this but controller gives the error is UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'path' of undefined For these two lines imgURL: req.file.path, whitePaperLink: req.file.path, the image and pdf are saved to folder not database but it gives the path error
Have you checked in req.files?
Sir When I check req.files console gives following result [Object: null prototype] { imgURL: [ { fieldname: 'imgURL' } ] } [Object: null prototype] { imgURL: [ { fieldname: 'imgURL' } ], whitePaperLink: [ { fieldname: 'whitePaperLink' } ] } When I check file console gives following result { fieldname: 'imgURL', originalname: 'youtube.png', encoding: '7bit', mimetype: 'image/png' } { fieldname: 'whitePaperLink', originalname: 'ReactTask.pdf', encoding: '7bit', mimetype: 'application/pdf' }
I have try this updated code but it gives the error is req.files.imgURL[0].path.replaceAll is not a function , I have try replace function insted of replaceAll but it gives the same error is like UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'path' of undefined
Can you send the response of req.files?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.