0

`

const mongoose = require('mongoose');

const postSchema = new mongoose.Schema(
{
    content: 
    {
        type: String,
        required: true
    },
    user:
    {
        type:mongoose.Schema.Types.ObjectId,
        ref:'User'
    },
    comments:
    [
        {
            type:mongoose.Schema.Types.ObjectId,
            ref:'Comment'
        }
    ],
    likes:
    [
        {
            type:mongoose.Schema.Types.ObjectId,
            ref:'Like'
        }
    ]

}, {timestamps: true});

postSchema.pre('find', function (next) 
{ 
    this.populate('user');
    next();
})
/*.pre('find', function (next) 
{
    this.populate('comments');
    next();
});*/

const Post = mongoose.model('Post', postSchema);

module.exports = Post;

In this code my user field is populating correctly But if try to populate the comments field the control gets stuck in infinite recursion. To avoid that I also used

postSchema.pre('find', function (next) {
  if (this.options._recursed) {
    return next();
  }
  this.populate({ path: "comments", options: { _recursed: true } });
  next();
});

`

as mentioned in official mongoose documentation here but still it is not working.

On the other hand in controller part if populate like this

`

 const posts = await Post.find({}).populate('comments').sort('-createdAt');

`

and in Post model if populate only user field

`

postSchema.pre('find', function (next) 
{ 
    this.populate('user');
    next();
})

`

Then this code is working perfectly fine. I want to know why comments field is not getting populated in the Post model. Please help me.

Trying to populate the comments field in Post model

0 Answers0