2

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
}
2
  • Where in the code did you specify the Mongoose.model function? Commented Dec 29, 2021 at 18:59
  • @Tyler2P at the end of the Schemas. I've just added them to code Commented Dec 29, 2021 at 19:02

2 Answers 2

2

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'});
Sign up to request clarification or add additional context in comments.

Comments

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')
    }
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.