【发布时间】:2019-05-05 04:50:13
【问题描述】:
我正在从 nodejs/expressjs 中的 mysql 数据库中获取数据,并希望从中创建嵌套的 json。
我想像这样创建 Json 对象:
[
{id : 1,countryName:'USA',population:10000,
cities : [
{id:1,cityName:'NY',countryId:1},{id:2,cityName:'Chicago',countryId:1}
]
},
{id : 2,countryName:'Canada',population:20000,
cities : [
{id:1,cityName:'Toronto',countryId:2},{id:2,cityName:'Ottawa',countryId:2}
]
}
]
这是我在 expressJs 中的代码,但它给了我一个空的 JSON 数组
app.get("/checkJson",function(req,res){
var country = {};
var outerobj = {};
var outerArray = [];
conn.query("select * from country",function(err,result){
for(var i = 0 ;i<result.length;i++){
var cityobj = {};
var city = [];
conn.query("select * from city where countryId ="+result[i].id,function(err,cityResult){
for(var j = 0;j<cityResult.length;j++){
cityobj = {cityName:cityResult[j].name,countryId:cityResult[j].countryId};
city.push(cityobj);
} //end city forloop
}) //end city Query
outerobj = {id:result[i].id,countryName:result[i].name,pop:result[i].population,cities:city};
outerArray.push(outerobj);
} //end country forloop
}) // end country query
console.log(outerArray);
})
【问题讨论】:
-
在 Javascript 中,所有动作都发生在回调中。在您的第一个查询完成之前调用示例末尾的
console.log()调用,不要介意您的嵌套查询。处理这种情况的一种方法是使用 async / await(或 Promises)。很抱歉,解释这超出了 Stack Overflow 答案的范围。 -
你能给我一个链接或其他东西让我可以了解它吗?
-
建议:使用你喜欢的搜索引擎寻找nodejs mysql promise。您会发现许多有用的资源。
-
谢谢先生 :)
标签: mysql node.js json express