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

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

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

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 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