I'm using a mongodb to create the REST API for an express app with node.js.
I created three different schemes that are somehow related to each other e.g. a book was written by an author and published by a publisher. Here is the scheme for the book.
const mongoose = require('mongoose')
const bookSchema = new mongoose.Schema({
title: {
type: String,
required: true
},
author: {
type: {type: mongoose.Schema.Types.ObjectId, ref: 'Author'},
},
publisher: {
type: {type: mongoose.Schema.Types.ObjectId, ref: 'Publisher'},
},
isbn: {
type: String,
required: true
},
})
module.exports = mongoose.model('Book', bookSchema)
Each of those schemes has an id, but I'm using the default id that is generated when posting an object.
Here is a part of the route-file.
//Creating one Book
router.post('/', async (req, res) => {
const book = new Book({
title: req.body.title,
author: req.body.author.findById,
publisher: req.body.publisher.findById,
isbn: req.body.isbn
})
try {
const newBook = await book.save()
res.status(201).json(newBook)
} catch {
res.status(400).json({message: err.message})
}
})
I am using a .rest-file for testing.
###
POST http://localhost:3000/books
Content-Type: application/json
{
"title" : "test",
"author" : "615c429dfe31a3863b6ebc8e", //object_id of an author in the db
"publisher" : "615f3daf330081bcd5010861", //object_id of a publisher in the db
"isbn" : "1234"
}
When I run this statement it will just create an object containing the object_id, a title and an isbn. The author and the publisher are left out. I did not set author and publisher as required in the scheme because it would throw an error (failed to cast string to object_id). I already tried that.
Can anyone please tell me how to avoid this casting error? I already googled and watched tutorials, but i did not find anything, yet.
Thank you.
There is difference between Mongoose and MongoDB native driver. Mongoose will automatically convert(Typecast) into Type defined in schema.
Your schema looks fine, you just need to change it like
//Creating one Book
router.post('/', async (req, res) => {
const book = new Book({
title: req.body.title,
author: req.body.author,
publisher: req.body.publisher,
isbn: req.body.isbn
})
try {
const newBook = await book.save()
res.status(201).json(newBook)
} catch {
res.status(400).json({message: err.message})
}
})