So I'm trying to insert a nested document here. books contains multiple book but it doesn't insert a title, only auto generated _id.
here's my code inserting a data:
"firstName": "Jay Rhick",
"lastName": "Villareal",
"country": "Philippines",
"citizenship": "Filipino",
"books": [{
"book": "Harry Pota"
}]
and here's the output:
{
"_id": "6053fc2f33325b35305ee764",
"firstName": "Jay Rhick",
"lastName": "Villareal",
"country": "Philippines",
"citizenship": "Filipino",
"books": [
{
"_id": "6053fc2f33325b35305ee765"
}
],
"__v": 0
Here's my Schema:
const mongoose = require('mongoose')
const BookSchema = require('./BookSchema').schema
const PostSchema = mongoose.Schema({
firstName: String,
lastName: String,
citizenship: String,
country: String,
books: [BookSchema]
})
module.exports = mongoose.model('PostSchema', PostSchema)
here's my book schema
const mongoose = require('mongoose')
const BookSchema = mongoose.Schema({
book: String
})
module.exports = mongoose.model('BookSchema', BookSchema)
and here's my express routes
const express = require('express')
const router = express.Router()
const Post = require('../models/Post')
router.post('/', async (req, res) => {
const post = new Post({
firstName: req.body.firstName,
lastName: req.body.lastName,
country: req.body.country,
citizenship: req.body.citizenship,
books: [{
book: req.body.book
}]
})
try{
const savedPost = await post.save()
res.json(savedPost)
}catch(err){
res.json({ message: err })
}
})
module.exports = router