0

I am trying to make some nested population. User model is populated the way i expect it to be.

But i am having trouble with nested population of a Post model. It's not populated at all.

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

mongoose.connect(`mongodb://localhost:27017/testDB`);

var UserSchema = new Schema({
    name:String,
    post: {
        type: Schema.Types.ObjectId,
        ref: 'Post'
    }
});
var PostSchema =  new Schema({
    title:String,
    subscriber:{
        type:Schema.Types.ObjectId,
        ref:'Subscriber'
    }
});

var SubscriberSchema = new Schema({
    name:String
});

var User =  mongoose.model("User", UserSchema);
var Post = mongoose.model('Post',PostSchema);
var Subscriber = mongoose.model('Subscriber',SubscriberSchema);

User
    .find()
    .populate([{
        path:'post',
        model:'Post',
        populate:{
            model:'Subscriber',
            path:'subscriber'
        }
    }])
    .exec()
    .then(function(data){
        console.log(data);
        mongoose.disconnect();
    });
Praveen Reddy
  • 7,295
  • 2
  • 21
  • 43

1 Answers1

0

You are calling .populate incorrectly. Please try this:

User
 .find()
 .populate('post')
 .populate({
  path: 'post',
  populate: {
   path: 'subscriber',
   model: 'Subscriber'
  }
 })
 .exec()
 .then(function (data) {
  console.log(data);
  mongoose.disconnect();
 });

For more info check this out.

Community
  • 1
  • 1
Antonio Narkevich
  • 4,206
  • 18
  • 28