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

380
Views
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 answers
Answer question

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 Report

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