我有一个标签集合,它们只有一个值,即标签。它们可以是随机标签或树标签(这里是没有 的示例_id
):
{
"label": "/test1"
}
{
"label": "/test2"
}
{
"label": "/test1/test1-1"
}
{
"label": "/test2/test2-1"
}
{
"label": "/test1/test1-1/test1-1-1"
}
{
"label": "something"
}
我想要的是有一个带有标签树的对象:
{
"/test1": {
"name": "test1"
, "children": {
"/test1/test1-1" : {
"name": "test1-1"
, "children": {
"/test1/test1-1/test1-1-1" : {
"name": "test1-1-1"
, "children": {}
}
}
}
}
}
, "/test2": {
"name": "test2"
, "children": {
"/test2/test1-2" : {
"name": "test1-2"
, "children": {}
}
}
}
}
这是我在我的应用程序中尝试过的:
app.get('/tree', function(req, res, next) {
var tree = {};
Tag
// If you have a better solution, I'm not really fan of this
.$where('this.label.split(new RegExp("/")).length === 2')
.exec(function(err, tags) {
tags.forEach(function(tag) {
tag.getChildren(function(children) {
tree[tag.label] = {
'title': tag.label
, 'children': children
}
});
});
});
// do some stuff with the `tree` var
// which does not work because of the asynchronousity of mongo
});
在我的模型中,它不起作用,起初我想用 with 返回树的路径,tag.getChildren()
但后来,我认为回调将是一个更好的选择,我停在那里。
Tag.methods.getChildren = function(callback) {
var tree = {};
Tag
.$where('this.label.split(new RegExp("' + this.label + '/")).length === 2')
.exec(function(err, tags) {
tags.forEach(function(tag) {
tag.getChildren(function(children) {
tree[tag.label] = {
'title': tag.label
, 'children': children
}
});
});
return tree
});
};
我不知道该怎么做,我对 Node 和异步编程还很陌生,所以任何帮助都将不胜感激。