Estoy intentando hacer una base de datos noSQL de una tienda de libros. Cuando estoy definiendo el esquema de libros, intento relacionar ese modelo con otro modelo ya creado y obtengo un error en consola.
Lo que trato de hacer es salvar la información proveniente del frontend del libro pero la información del autor, y genero guardarla con un id diferente pero que estén relacionados con el modelo de libro.
Error:
'Cast to Embedded failed for value "Techno-thriller" at path "genre"',
name: 'CastError',
stringValue: '"Techno-thriller"',
kind: 'Embedded',
value: 'Techno-thriller',
path: 'genre',
reason: [MongooseError] } },
_message: 'Books validation failed',
name: 'ValidationError' }
controller.js:
controller.createBook = (req, res) => {
const name = req.body.name;
const author = req.body.author;
const genre = req.body.genre;
const numberInStock = req.body.numberInStock;
const image = req.body.image;
let newBook = {
name: name,
author: author,
genre: genre,
numberInStock: numberInStock,
image: image,
};
Books.create(newBook, (err, newlyCreated) => {
if (err) {
console.log(err);
} else {
res.redirect('/books/home/1');
}
});
model.js:
const mongoose = require('mongoose');
const { genreSchema } = require('./genres');
const { authorSchema } = require('./author');
const booksSchema = new mongoose.Schema({
name: String,
author: {
type: authorSchema,
},
numberInStock: Number,
image: String,
genre: {
type: genreSchema,
},
});
// const Books = mongoose.model('Book', booksSchema);
// exports.booksSchema = booksSchema;
// exports.Books = Books;
module.exports = mongoose.model('Books', booksSchema);
view.ejs*:
<div class="container h-100">
<div class="row">
<div class="col-lg-6 col-md-offset-3">
<h1>Add a New Book</h1>
<form action="/books/new/create" method="post">
<div class="panel panel-default">
<div class="panel-body">
<div class="form-group">
<label for="book_name"> Book Name: </label>
<input type="text" class="form-control" name="name">
</div>
<div class="form-group">
<label for="author_name">Author Name: </label>
<input type="text" class="form-control" name="author">
</div>
<div class="form-group">
<label for="genre">Book genre: </label>
<input type="text" class="form-control" name="genre">
</div>
<div class="form-group">
<label for="numberInStock">Number in stock: </label>
<input type="number" class="form-control" name="numberInStock">
</div>
<div class="form-group">
<label for="image">Image: </label>
<input type="text" class="form-control" name="image">
</div>
<button type="submit" class="btn btn-success">Success</button>
</div>
</div>
</form>
</div>
</div>
</div>