DEV Community

Cover image for Mongoose populate: How to query multi-level document
Ambroise BAZIE
Ambroise BAZIE

Posted on • Edited on

4 2

Mongoose populate: How to query multi-level document

Sometimes you want to populate more than one level deep a schema using mongoose. i will share with you today how i use pure mongoose populate method to access more than one level deep data relation.

Suppose you have a User model that has many Posts and each post has Category.

Here we are going to retrieve a user with all posts that are not deleted with the category name and description populated.

Models

import * as mongoose from 'mongoose';
import { Schema } from 'mongoose';

// Category schema
export const categorySchema = new Schema({
    categoryName: {type: String, unique: true},
    description: {type: String},
    isDeleted: {type: Boolean, default: false}
}, {timestamps: true});

// Post schema
const postSchema = new Schema({
    title: { type: String },
    description: { type: String },
    category: { type: Schema.Types.ObjectId, ref: "Category"},
    isDeleted: { type: Boolean, default: false }
});

// User schema
const userSchema = new Schema({
    username: { type: String, unique: true },
    email: { type: String, unique: true },
    posts: [
     { type: Schema.Types.ObjectId, ref: "Post" }
    ]
});

export const Category = mongoose.model('Category', categorySchema);
export const Post = mongoose.model('Post', postSchema);
export const User = mongoose.model('User', userSchema);
Enter fullscreen mode Exit fullscreen mode

Query

// Query to get all posts with the category 
const userWithPosts = await User.findById(id).populate({
   path: 'posts',
   model: Post,
   match: { isDeleted: false },
   populate: {
      path: 'category',
      model: Category,
      select: "categoryName description"
   }
}).exec();

Enter fullscreen mode Exit fullscreen mode

Thanks

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post

Top comments (2)

Collapse
 
josemfcheo profile image
José Martínez

LOVE YOUUUUU

Collapse
 
ognanshissi profile image
Ambroise BAZIE

Hope it helped

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay