我使用Mongoose.js并不能解决3级层次文档的问题.
有两种方法可以做到这一点.
首先 - 没有参考.
C = new Schema({
'title': String,
});
B = new Schema({
'title': String,
'c': [C]
});
A = new Schema({
'title': String,
'b': [B]
});
Run Code Online (Sandbox Code Playgroud)
我需要显示C记录.我怎么能填充/找到它,只知道C的_id?
我试着用:
A.findOne({'b.c._id': req.params.c_id}, function(err, a){
console.log(a);
});
Run Code Online (Sandbox Code Playgroud)
但是我不知道如何从者返回一个只有我需要的对象的对象.
第二,如果使用refs:
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' }]
});
Run Code Online (Sandbox Code Playgroud)
如何填充所有B,C记录以获得层次结构?
我试着用这样的东西:
A
.find({}) …
Run Code Online (Sandbox Code Playgroud) 我在MongoDB中有这个设置
项目:
title: String
comments: [] // of objectId's
Run Code Online (Sandbox Code Playgroud)
评论:
user: ObjectId()
item: ObjectId()
comment: String
Run Code Online (Sandbox Code Playgroud)
这是我的Mongoose架构:
itemSchema = mongoose.Schema({
title: String,
comments: [{ type: Schema.Types.ObjectId, ref: 'comments' }],
});
Item = mongoose.model('items', itemSchema);
commentSchema = mongoose.Schema({
comment: String,
user: { type: Schema.Types.ObjectId, ref: 'users' },
});
Comment = mongoose.model('comments', commentSchema);
Run Code Online (Sandbox Code Playgroud)
这是我得到我的项目和评论的地方:
Item.find({}).populate('comments').exec(function(err, data){
if (err) return handleError(err);
res.json(data);
});
Run Code Online (Sandbox Code Playgroud)
如何使用相应的用户填充注释数组?由于每条评论都有一个用户ObjectId()?