Answer the question
In order to leave comments, you need to log in
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();
});
Answer the question
In order to leave comments, you need to log in
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();
[
{
"_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 questionAsk a Question
731 491 924 answers to any question