I want to insert my book to Collection Book. In book, i have field author is a part of another Collection called Author. I try to insert the book but i got Mongoose casterror. This is my code:
const mongoose = require('mongoose')
const path = require('path')
const coverImageBasePath = 'uploads/bookCovers'
const bookSchema = new mongoose.Schema({
title: {
type: String,
required: true
},
description: {
type: String
},
publishDate: {
type: Date,
required: true
},
pageCount: {
type: Number,
required: true
},
createdAt: {
type: Date,
required: true,
default: Date.now
},
coverImageName: {
type: String,
required: true
},
author: {
type: mongoose.Types.ObjectId,
required: true,
ref: 'Author'
}
})
module.exports = mongoose.model('Book', bookSchema)
And this is post router to create a book
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 (err) {
console.log(err)
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')
}
}
I tried some solution and googled but it did not work, when i insert straightly author by String, it works so i think the bug is in the mongoose Schema but i can not find out the way to solve it. Please help me.