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);
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();
Top comments (2)
LOVE YOUUUUU
Hope it helped