Search code examples
javascriptmongodbmongoosemongoose-schema

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

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.