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

Question:

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:

eBook.js

const express = require("express");
const router = express.Router();
const mongoose = require("mongoose");
const User = mongoose.model('users');
const requireDir = require('require-dir');
requireDir('../models');
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 }
]);

router.post('/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(!req.body.author || typeof req.body.author == undefined || req.body.author == null){
        erros.push({texto: "Autor inválido"})
    }

    if(erros.length > 0){
        res.render("pages/ebooks/create", {erros: erros})
    }else{
        const filename = req.file.filename;
        const newBook = {
            title: req.body.title,
            author: req.body.author,
            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!")
            res.redirect("/ebook/galeria")
            console.log(newBook)
        }).catch(function(err){
            console.log(err)
            req.flash("error_msg", "Houve um erro ao salvar o eBook! Tente novamente")
            res.redirect("/ebook/galerias")
        })
    }
});

Answer:

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

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