First = new mongoose.Schema({
name: String,
second: {type: Schema.Types.ObjectId, ref: 'Second'},
});
Second = new mongoose.Schema({
name: String,
third: {type: Schema.Types.ObjectId, ref: 'Third'},
});
Third = new mongoose.Schema({
name: String
});
First.find({}).populate({
path: 'Second',
populate: { path: 'Third'}
}).exec(function(err, result) {
console.log(result)
})
首先填充是好的,但第三个总是null
。意思是我有这样的事情:
{
name: 1,
second: {
name: 2,
third: null
}}
答案 0 :(得分:1)
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/test');
var FirstSchema = new mongoose.Schema({
name: String,
second: {type: Schema.Types.ObjectId, ref: 'Second'},
});
var SecondSchema = new mongoose.Schema({
name: String,
third: {type: Schema.Types.ObjectId, ref: 'Third'},
});
var ThirdSchema = new mongoose.Schema({
name: String
});
var First = mongoose.model('First', FirstSchema);
var Second = mongoose.model('Second', SecondSchema);
var Third = mongoose.model('Third', ThirdSchema);
First.remove({}).exec();
Second.remove({}).exec();
Third.remove({}).exec();
var _3 = new Third({name: 'third'});
_3.save(function(err1) {
if (err1) {
throw err1;
}
var _2 = new Second({name: 'second', third: _3.id});
_2.save(function(err2) {
if (err2) {
throw err2;
}
var _1 = new First({name: 'first', second: _2.id});
_1.save(function() {
First.find({}).populate({
path: 'second',
populate: { path: 'third'}
}).exec(function(err, result) {
console.log(result[0]);
});
});
});
});
您的path
是否由错误的值分配?
它应该是字段名称,而不是对象名称