我正在使用带有父引用的模型树结构,如下所示:
{
"_id" : "YezvuyCowZdo2ZLgX",
"title" : "Main",
"type" : "section",
}
{
"_id" : "eYkxs8rW3dKH5SfoE",
"title" : "element 1",
"order" : 1,
"type" : "element",
"parent" : "YezvuyCowZdo2ZLgX"
}
{
"_id" : "siaRPzaTgDrfWZ7kn",
"title" : "subelement 1",
"order" : 1,
"type" : "element",
"parent" : "ASkJZSkPAj8mhb7An"
}
{
"_id" : "DrfWZ7knsiaRPzaTg",
"title" : "subelement 2",
"order" : 2,
"type" : "element",
"parent" : "ASkJZSkPAj8mhb7An"
}
{
"_id" : "XZF9hpW8ZqTnRdkEg",
"title" : "element 2",
"order" : 3,
"type" : "element",
"parent" : "YezvuyCowZdo2ZLgX"
}
{
"_id" : "ASkJZSkPAj8mhb7An",
"title" : "group 1",
"type" : "group",
"parent" : "YezvuyCowZdo2ZLgX",
"order" : 2
}
但现在我需要的信息是'等级'一个元素属于。如何获得包含此信息的新字段?
eYkxs8rW3dKH5SfoE -> add field { level: 1 }
siaRPzaTgDrfWZ7kn -> add field { level: 2 }
DrfWZ7knsiaRPzaTg -> add field { level: 2 }
XZF9hpW8ZqTnRdkEg -> add field { level: 1 }
ASkJZSkPAj8mhb7An -> add field { level: 1 }
所以我想我必须为所有主要元素执行每个循环,从{ type: 'section'}
开始。
Collection.find({ type: 'section'}).each(function(doc) {
Collection.update({ parent: doc._id }, { $set: { level: 1 }});
// go to next subelement and increase level until there is no child
});
但是如何通过树来设置所有级别?