【问题标题】:Adding elements to a json while making queries to the database在对数据库进行查询时将元素添加到 json
【发布时间】:2015-05-31 22:33:20
【问题描述】:

在对数据库进行查询时,我在操作 json 时遇到了问题。我有一个具有以下属性的表类型:id、name、parent_id。我想获取每个 id=null 的流派,并为每个流派添加属性 children 以及 parent_id 等于其 id 的流派。

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

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 中。

【问题讨论】:

    标签: json node.js asynchronous


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      你试过这个吗?

          item.children = items;
      

      【讨论】:

      • 我解决了,没有错误,只是我没有及时发送响应,这意味着查询没有完成,所以我不得不等待所有回调被退回。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 2019-10-03
      • 2016-01-28
      • 1970-01-01
      相关资源
      最近更新 更多