无法将项目添加到MongoDB

时间:2020-02-25 18:23:16

标签: javascript node.js mongoose

我无法将书添加到MongoDB中。我填写了Web应用程序中的所有字段,并创建了按钮,但出现错误消息。这是我的代码:

// Create Book route
router.post('/', upload.single('cover'), async (req, res) => {
    const fileName = req.file != null ? req.file.filename : null;
    const book = new Book({
        title: req.body.title,
        author: req.body.author,
        publishDate: new Date(req.body.publishDate),    
        pageCount: req.body.pageCount,
        coverImageName: fileName,
        description: req.body.description
    });
    try {
        const newBook = await book.save();
        //res.redirect(`books/${newBook.id}`);
        res.redirect(`books`);
    } catch {
        if (book.coverImageName != null) {
            removeBookCover(book.coverImageName);
        }
        renderNewPage(res, book, true);
    }
});

async function renderNewPage(res, book, hasError = false) {
    try {
        const authors = await Author.find({});
        const params = {
            authors: authors,
            book: book
        }
        if (hasError) params.errorMessage = 'Error Creating Book'
        res.render('books/new', params);
    } catch {
        res.redirect('/books')
    }
}

我的架构:书和作者是正确的。

0 个答案:

没有答案