在查询数据库时向 json 添加元素

Adding elements to a json while making queries to the database

我在查询数据库时遇到了操作 json 的问题。我有一个具有以下属性的 table 流派:id、名称、parent_id。我想获得每个具有 id=null 的流派,并为每个流派添加具有 parent_id 等于其 id 的流派的属性 children。

这是我到目前为止所做的:

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);
    }
})

} 我得到了我想要的项目,我只是不知道如何将它们添加到 json。

你试过这个吗?

    item.children = items;

好的,我发现了我的错误,这工作正常:

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);
      });
    }
  })
}