Populate a nested schema with Model having nested schema in mongoose

User Model with categorySchema nested into userSchema:

const categorySchema = new mongoose.Schema({
  categoryName: {
    type: String,
    maxlength: [40, 'Expense name must not be more than 40 characters'],
  },
  categoryValue: {
    type: String,
  },
)

const userSchema = new mongoose.Schema({
  fullName: {
    type: String,
    trim: true,
    required: [true, 'Full Name is required'],
  },
categoriesData: {
    type: [categorySchema],
},
);

const User = mongoose.model('User', userSchema);

Budget model with revenueSchema nested into budgetSchema ,

const revenueSchema = new mongoose.Schema({
  categoryData: {
    type: mongoose.Schema.ObjectId,
    ref: 'User',
  }
)

const budgetSchema = new mongoose.Schema({
   revenueData: { type: [revenueSchema] }
})

//My Code for populate
budgetSchema.pre(/^find/, function (next) {
  this.populate({
    path: 'revenueData',
    populate: [
      {
        path: 'categoryData',
        select: '-__v -_id',
      },
    ],
  });

  next();
});

const Budget = mongoose.model('Budget', budgetSchema);

In revenueSchema , the categoryData property contains the object Id of document created in categorySchema which is nested in User Model. So whenever there is a ‘find’ query in Budget Model, I want to populate categoryData in Budget model with it’s corresponding id document from categorySchema in User Model. I have tried, but I am getting null as response in categoryData.

Please help

2 Likes