node.js – TypeError: Cannot read property ‘filename’ of undefined


I intend to save the file in the uploads folder and save the file name in the bank. console.log() shows me this:

{theBook: undefined, cover: undefined}

It saves the image in the uploads folder but doesn't file the name in the BD , coming as undefined .

Why am I getting this result?:

TypeError: Cannot read property 'filename' of undefined

My file:


const express = require("express");
const router = express.Router();
const mongoose = require("mongoose");
const User = mongoose.model('users');
const requireDir = require('require-dir');
const eBook = mongoose.model('books');
const multer = require('multer');
const uploadConfig = require('../config/upload');

const upload = multer(uploadConfig);
var eBookUpload = upload.fields([
{ name: 'cover', maxCount: 1 }, 
{ name: 'theBook', maxCount: 1 }
]);'/add', eBookUpload, async (req, res, next) => {
    var erros = []

    if(!req.body.title || typeof req.body.title == undefined || req.body.title == null){
        erros.push({texto: "Título inválido"})

    if(! || typeof == undefined || == null){
        erros.push({texto: "Autor inválido"})

    if(erros.length > 0){
        res.render("pages/ebooks/create", {erros: erros})
        const filename = req.file.filename;
        const newBook = {
            title: req.body.title,
            genre: req.body.genre,
            publisher: req.body.publisher,
            edition: req.body.edition,
            isbn: req.body.isbn,
            pages: req.body.pages,
            theBook: filename,
            cover: filename,
            type: req.body.type,

        new eBook(newBook).save().then(function(){
            req.flash("success_msg", "eBook adicionado com sucesso!")
            req.flash("error_msg", "Houve um erro ao salvar o eBook! Tente novamente")


The problem is that you have an array of files, so it would be:

const filename = req.files[index].filename;
Scroll to Top