I am having trouble with manipulating a json while making queries on the database. I have a table Genre with the following attributes : id, name, parent_id. I want to get every genre that has an id=null and for each of them, add the attribute children with the genres that have a parent_id equal to their id.
Here is what I have done so far:
getGenres: function (req, res) {
Genres.find().where({parent_id : null}).exec(function(err, elements) {
if (err)
console.log(err);
else {
async.each(elements, function(item, callback) {
Genres.find().where({parent_id: item.id}).exec(function(err, items) {
console.log(items);
item['children'] = items; //Doesn't work but that's the idea
callback();
})
})
res.send(elements);
}
})
} I am getting the items I want, I just don't know how to add them to the json.
Did you tried this instead ?
item.children = items;
Ok, I found my mistake, this works correctly :
getGenres: function (req, res) {
Genres.find().where({parent_id : null}).exec(function(err, elements) {
if (err)
res.send(err);
else {
async.each(elements, function(item, callback) {
Genres.find().where({parent_id: item.id}).exec(function(err, items) {
item.children = items;
callback();
})
}, function(err) {
if (err)
res.send(err);
res.send(elements);
});
}
})
}