我有一个类似于这样的数据结构:
var GrandGrandChild = mongoose.Schema({
attribute: String,
id: Number
});
var GrandChild = mongoose.Schema({
children: [GrandGrandChild],
id: Number,
irrelevantAttribute: String
});
var Child = mongoose.Schema({
children: [GrandChild],
id: Number,
irrelevantAttribute2: String
});
var Parent = mongoose.Schema({
children: [Child],
id: Number,
irrelevantAttribute3: String
});
var GrandParent = mongoose.Schema({
children: [Parent],
id: Number,
irrelevantAttribute4: String
});
这些集合中包含许多子文档。请注意,ID对于其同级元素是唯一的,但对于具有相同模式的所有元素而言并不唯一。
因此,一个祖先可以拥有一个ID为0的父代,另一个祖先也可以拥有一个ID为0的父代。但是,一个祖先不能拥有2个ID为0的父代。
唯一保存的架构是GrandParent架构,mongoose/mongodb将这个祖先的所有数据制成一个很好的大型单一文档。(正是我正在寻找的)
所以问题来了:我有一个GrandParent ID、Parent ID、Child ID、GrandChildID和GrandGrandChild ID,我想以某种方式仅获取所有这些ID指向的GrandGrandChild对象。
丑陋的方法是,但目前我能够使之工作的唯一方法是,创建一个查询来获取这个GrandParent的大型文档,并手动循环遍历所有数组以找到正确的Parent,然后再次循环以找到正确的child,然后再次循环以找到正确的grandchild,最后再次循环并找到我需要的grandgrandchild。
我的问题是,我该如何在mongoose中组合一个查询,它要么只返回grandgrandchild文档,要么返回只包含children属性的grandparent文档,其中,在该children属性中仅包含引用到grandgrandchild对象的grandchild对象、引用到该grandchild对象的child对象和引用到该child对象的parent对象,从而实现以下结果:
GRANDPARENT PARENT CHILD GRANDCHILD GRANDGRANDCHILD
grandparent.children[0].children[0].children[0].children[0].attribute;
我希望有人能够帮助我解决这个问题,目前我所知道的是:
GrandParentModel.findOne(
{
"id" : 0,
"children.id" : 0,
"children.children.id" : 0,
"children.children.children.id" : 0,
"children.children.children.children.id" : 0
},
{"children.children.children.children.$" : 1}, callback);
这个查询的问题在于没有削减掉不必要的兄弟节点。
希望有人能帮我一下。
Hylke Bron