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