如何处理猫鼬嵌套人口?

时间:2017-02-17 23:35:01

标签: node.js mongodb mongoose

我正在尝试制作一些嵌套的人口。用户模型以我期望的方式填充。

但我遇到Post模型的嵌套人口问题。它根本没有填充。

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

1 个答案:

答案 0 :(得分:0)

您正在正确调用.populate。 请试试这个:



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




有关详情,请查看this