我使用Mongoose.js,但无法解决三级层次文档问题。
有两种方法可以解决。
第一种 - 不使用引用。
C = new Schema({
'title': String,
});
B = new Schema({
'title': String,
'c': [C]
});
A = new Schema({
'title': String,
'b': [B]
});
我需要展示C记录。如果只知道C的_id,如何填充/查找它呢?
我尝试使用:
A.findOne({'b.c._id': req.params.c_id}, function(err, a){
console.log(a);
});
但是我不知道如何从返回一个对象,只获取我需要的C对象。
第二,如果使用引用:
C = new Schema({
'title': String,
});
B = new Schema({
'title': String,
'c': [{ type: Schema.Types.ObjectId, ref: 'C' }]
});
A = new Schema({
'title': String,
'b': [{ type: Schema.Types.ObjectId, ref: 'B' }]
});
如何填充所有的B、C记录以获取层级结构?
我尝试使用以下代码:
A
.find({})
.populate('b')
.populate('b.c')
.exec(function(err, a){
a.forEach(function(single_a){
console.log('- ' + single_a.title);
single_a.b.forEach(function(single_b){
console.log('-- ' + single_b.title);
single_b.c.forEach(function(single_c){
console.log('--- ' + single_c.title);
});
});
});
});
但是对于single_c.title它会返回未定义。有方法可以填充它吗?
谢谢。