我正在尝试编写一个nodejs脚本,该脚本从mongodb中的多个集合中获取数据。之后,必须将完整的数据写入一个json响应中。 目前我所采用的方法是将每个集合中的json数据推送到一个数组中,然后将该数组作为响应发送。但在客户端脚本中我无法读取数据。 我编写的用于编写响应的代码(Router.js)是:
appTableProdSchema.js
var conn = require('mongoose');
module.exports = conn.model('AppTableProd', {
snapShotTime : String,
nfs: Array,
hive: Array,
beeline: Array,
hs2: Array,
beeswax: Array,
df: Array
});
hs2_10010Schema.js
var conn = require('mongoose');
module.exports = conn.model('hiveserver2_10010', {
snapShotTime : String,
hs2: Array
});
Router.js
var moment = require('moment'); //add moment
var records;
//mongoose schema
var appTableProdSchema = require("./appTableProdSchema.js");
var hs2 = require("./hs2_10010Schema.js");
router.get('/getHealthReport', function(req, res) {
// Return the most recent document
var fullData = [];
records = appTableProdSchema
.find()
.sort({'_id': -1})
.limit(1)
.exec(function(err, data) {
if (err) return res.sendStatus(500);
fullData.push(data);
});
records = hs2
.find()
.sort({'_id': -1})
.limit(1)
.exec(function(err, data) {
if (err) return res.sendStatus(500);
fullData.push(data);
res.json(fullData);
});
});
module.exports = router;
我在Response中看到的数据是:
[
[{
"_id":"56f178cf64dadf6411ccc3fa",
"snapShotTime":"2016-03-22-16:50:05",
"__v":0,
"df":["data_node_1","data_node_2","data_node_3","data_node_4","data_node_5","data_node_13","data_node_10","data_node_9","data_node_6","data_node_8","data_node_12","data_node_7","data_node_11","ebdp-ch2-d146p.sys.comcast.net","ebdp-ch2-d192p.sys.comcast.net"],
"beeswax":["data_node_10","data_node_1","data_node_11","data_node_13","data_node_4","data_node_2","data_node_3","data_node_6","data_node_12","data_node_5","data_node_7","data_node_8"],
"hs2":["data_node_7","data_node_1","data_node_10","data_node_13","data_node_4","data_node_3","data_node_2","data_node_9","data_node_11","data_node_5","data_node_8","data_node_6","data_node_12"],
"beeline":["data_node_10","data_node_1","data_node_11","data_node_13","data_node_4","data_node_2","data_node_3","data_node_6","data_node_12","data_node_5","data_node_7","data_node_8"],
"hive":["data_node_4","data_node_2","data_node_3","data_node_7","data_node_8","data_node_5","data_node_1","data_node_6","data_node_12","data_node_11","data_node_13","data_node_9","data_node_10"],
"nfs":["data_node_7","data_node_4","data_node_1","data_node_3","data_node_10","data_node_5","data_node_13","data_node_9","data_node_11","data_node_6","data_node_8","data_node_12","data_node_2"]
}],
[{
"_id":"56f178cf64dadf6411ccc3fb",
"snapShotTime":"2016-03-22 16:50:05",
"__v":0,
"hs2":["data_node_9"]
}]
]
我如何编码从数组中获取json对象?
答案 0 :(得分:0)
JSON对象中的数组有一个函数getJSONObject(int index),你可以使用for循环遍历所有这些:
var array;
for(int n = 0; n < array.length(); n++)
{
var object = array.getJSONObject(n);
// do some stuff....
}