M
M
Mariik2017-02-18 02:41:08
MongoDB
Mariik, 2017-02-18 02:41:08

What is the correct way to use .populate() in Mongoose?

Hello.
Something I'm completely confused with the population in mongus. There is this simple code:

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();
    });

It turns out that the User is filled with data from the Post model, but the Post itself does not receive data from the Subscriber model. And I don't understand why this is happening.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Kirill, 2017-02-18
@Mariik

I checked it myself, I could not reproduce the problem.
Created test data:

let s = new Subscriber({name:'Sn'});
let p = new Post({title:'Pt',subscriber:s });
let u = new User({name:'Un', post: p});

s.save();
p.save();
u.save();

After executing your code, I got the following result:
[
  {
    "_id": "58a81fd04396bb59443950e0",
    "name": "Un",
    "post": {
      "_id": "58a81fd04396bb59443950df",
      "title": "Pt",
      "subscriber": {
        "_id": "58a81fd04396bb59443950de",
        "name": "Sn",
        "__v": 0
      },
      "__v": 0
    },
    "__v": 0
  }
]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question