Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to load referenced document in Mongoose?

I have a MongoDB collection called categories which has a self-reference(parent) like follows.

const schema = mongoose.Schema({
    name: String,
    parent: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Category',
    }
});

export default mongoose.model('Category', schema);
When i query it just returns the object id of the referenced document.


{
"_id": "63731fe1ce1bf2f534f9307e",
"name": "Glass cleaners",
"parent": "63731fbbce1bf2f534f9307d",
}


I want to load the document referenced by `parent`, so i used following code to load the parent seperatly.

let parentCat = await Category.findOne({ _id: category.parent });

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


Is there an easy way of doing this because above is bit difficult to maintain if in my opinion.

Thanks

>Solution :

You can use query population in mongoose instead of querying parent again.

https://mongoosejs.com/docs/populate.html

You have to call populate() when you query which will load parent document.

 Category.find().populate('parent');

Highly suggest you to go through the mongoose documentation.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading