Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

132
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda