Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

381
Vistas
Can not populate array of objects

EDIT added mongoose.model.

I'm pretty new to mongodb and mongoose. I'm not able to populate books to authors in mongoose. Can anyone help me with that? Here is my code. I removed unnecessary fields

const authorSchema = mongoose.Schema({
    _id:{
        type: String,
        required: true,
        unique: true,
        trim: true
    },
    name: {
        type: String,
        required: true,
        trim: true
    },
    books: [{
        type: String,
        ref: "Book"
    }]
}, {_id:false})

const Author = mongoose.model('Author', authorSchema)

module.exports = {Author}

And my books schema looks as following

const bookSchema = mongoose.Schema({
    _id:{
        type:String,
        required:true,
        unique:true,
        trim: true
    },
    name: {
        type: String,
        required: true,
        trim: true,
        unique: true
    },
    description:{
        type: String,
        trim: true,
        default: 'No description specified'
    },
    datePublished: {
        type: Date,
        trim: true,
        default: '01/01/2001'
    },
    author:{
        type: String,
        ref: 'Author',
        required: true
    }
}, {_id:false})
const Book = mongoose.model('Book', bookSchema)

module.exports = {Book}

Here is the route to populate them together

AuthorRouter.get('/authors/:id', async(req, res)=>{
    const authorID = req.params.id
    try {
        const author = await Author.findById(authorID)
        try {
            const populated = await author.populate({path: 'books.book', select: 'name description -_id'})
            console.log(populated);
            res.status(201).send(populated)
        } catch (e) {
            res.status(401).send(`${e}\n Unable to populate categories`)
        }
        
    } catch (error) {
        res.status(401).send('Unable to find author')
    }
})

Output is following with empty books array:

{
    "_id": "123",
    "name": "testuser",
    "books": [],
    "__v": 0
}
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Populating an arrays of refs works the same way as a single ref. Just call the populate method on the query and an array of documents will be returned in place of the original _id's.

In your case that would be:

const populated = await author.populate({path: 'books', select: 'name description -_id'});
over 4 years ago · Santiago Trujillo Denunciar

0

Hey i have modify your code , try to use this one

This is your author schema file

const Schema = mongoose.Schema;
const authorSchema = mongoose.Schema({
    _id:{
        type: String,
        required: true,
        unique: true,
        trim: true
    },
    name: {
        type: String,
        required: true,
        trim: true
    },
    books: [{
        type: Schema.Types.ObjectId,
        ref: "bookSchema"
    }]
}, {_id:false})

const Author = mongoose.model('Author', authorSchema)

module.exports = {Author}

And this is your route


AuthorRouter.get('/authors/:id', async(req, res)=>{
    const authorID = req.params.id
    try {
        const author = await Author.findById(authorID)
        try {
            const populated = await author.find().populate('books');
            console.log(populated);
            res.status(201).send(populated)
        } catch (e) {
            res.status(401).send(`${e}\n Unable to populate categories`)
        }
        
    } catch (error) {
        res.status(401).send('Unable to find author')
    }
})
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda