UPD. PROBLEM SOLVED WITH ONE LINE OF CODE: .lean() axplanation here
I have this array of menu items after Model.find(...blablabla :
[
{"_id":"578763de6e8e0542195ef4e8",
"text":"lists", "iconCls":"fa fa-group fa-lg",
"className":null,
"menu_id":null},
{"_id":"578762146e8e0542195ef4e7",
"iconCls":"fa fa-group fa-lg",
"className":"panel",
"menu_id":"578763de6e8e0542195ef4e8",
"text":"personal"},
{"_id":"578770aca59f4d173c948376",
"text":"info",
"iconCls":"xf007",
"className":null,
"menu_id":null},
{"_id":"5787715aa59f4d173c94837c",
"text":"cars",
"className":"panel",
"menu_id":"578763de6e8e0542195ef4e8", "iconCls":"xf007"},
{"_id":"5787721ca59f4d173c94837f",
"text":"now" ,
"iconCls":"xf007",
"className":"xf007",
"menu_id":"578770aca59f4d173c948376"}]
And I want to build tree menu from them:
function buildMenu(source){
var menu = []; //Массив для нового, уже пирамидального меню
for (var i=0; i<source.length; i+=1){
if(source[i].menu_id === null){ //Выбираем верхние пункты меню
source[i].items = [];
for(var j=0; j<source.length;j+=1){
if(source[j].menu_id !== null){
if(source[i]._id.toString() == source[j].menu_id.toString()){
//найден дочерний пункт меню
source[i].items.push(source[j]);
}
}
}
menu.push(source[i]);
}
}
// Проверка
console.log(menu[0].items);
console.log(menu);
return menu;
}
So, when I trying to console.log my menu[0].items - I have them:
[ { _id: 578762146e8e0542195ef4e7,
iconCls: 'fa fa-group fa-lg',
className: 'panel',
menu_id: 578763de6e8e0542195ef4e8,
text: 'personal' },
{ _id: 5787715aa59f4d173c94837c,
text: 'cars',
className: 'panel',
menu_id: 578763de6e8e0542195ef4e8,
iconCls: 'xf007' } ]
But then, when I trying to return my new amazing menu, I get this:
[ { _id: 578763de6e8e0542195ef4e8,
text: 'lists',
iconCls: 'fa fa-group fa-lg',
className: null,
menu_id: null },
{ _id: 578770aca59f4d173c948376,
text: 'info',
iconCls: 'xf007',
className: null,
menu_id: null } ]
My God! Where is my items dissapeared!?!
Upd. I expecting to get something like this:
[ { _id: 578763de6e8e0542195ef4e8,
text: 'lists',
iconCls: 'fa fa-group fa-lg',
className: null,
menu_id: null
items: [
{ _id: 578762146e8e0542195ef4e7,
iconCls: 'fa fa-group fa-lg',
className: 'panel',
menu_id: 578763de6e8e0542195ef4e8,
text: 'personal' },
{ _id: 5787715aa59f4d173c94837c,
text: 'cars',
className: 'panel',
menu_id: 578763de6e8e0542195ef4e8,
iconCls: 'xf007' }
]
.....
Here is how I get my data:
.get('/menu', function(req,res){
var user_id = '5784b872a59f4d0f805a617d'; //пользователь boss/boss
User.find({_id:user_id})
.populate({
path: 'group',
populate: {
path: 'menu',
ref: 'Menu'
}
})
.exec(function(err,user) {
if (err) {
console.log(err.red, req.method, req.url);
res.status(500).end();
return err;
} else if (!user) {
res.status(404).end();
console.log(('Запрос вернул: ' + user).red);
} else {
res.status(200).send(buildMenu(user[0].group.menu));
}
});
//
})
MENUS:
USERS:
GROUPES:
I am realy confused...
Postman cant see them also:




