Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

130
Views
MongoDB doesn't insert nested document

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
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Since its a nested schema, it might not be returning the whole object, just the _id. Can you see the book with the title in your collection? If it is in the collection, you'll want to take a look at the .populate() function in mongoose.

heres a similar stackoverflow question: Populate nested array in mongoose

over 4 years ago · Santiago Trujillo Report

0

I solved my problem thanks to asg86260! So I have changed my code from:

  books: [{
    book: req.body.book
  }]

to books: req.body.books

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!