我需要将mongoose查询结果连接到单个JSON对象。 问题是我正在将数组传递给mongoose ie;
Modem Serial: [11111111111,nodata,3333333333333333]
我需要的是连接这样的数据;
Final Modem : [{"m_model":"Modem 1","m_serial_no":"11111111111","available":"dispatched"},
{"m_model":"No data","m_serial_no":"No data"},
{"m_model":"Modem3","m_serial_no":"3333333333333333","available":"dispatched"}]
这是我的代码;
for(i=0;i<modem_serial.length;i++){
console.log("Modem Serial: "+modem_serial[i]);
Modem.findOne({m_serial_no: modem_serial[i]},{_id: 0,__v:0},function (err,m_data) {
//console.log("err: "+err);
if(m_data!=null){
modem=modem.concat(m_data);
}else{
console.log("\n\n\nm_data : "+m_data);
modem=modem.concat({
m_model: 'No data',
m_serial_no: 'No data'
});
}
console.log("\n\n\nFinal Modem : "+JSON.stringify(modem));
});
}
但刷新后我得到了这个,
最终调制解调器:
[{"m_model":"No data","m_serial_no":"No data"},{"m_model":"Modem 1","m_serial_no":"11111111111","available":"dispatched"},{"m_model":"Modem 3","m_serial_no":"3333333333333333","available":"dispatched"}]
the `No data` is going to first index. why??
这是我的完整代码,
router.get('/', function(req, res, next) {
Dispatched.find({status:"installed"},function(err,dispatched_data) {
//console.log("SUCCES data: "+dispatched_data);
var client_name=[],branch_name=[],serial=[],data_card_serial=[],sim_number=[],modem_serial=[],idu_serial=[],installed_date=[],
ip_address=[],notes=[],ir_report=[],date,ipp={},ip=[],ir,note;
for (var j = 0; j < dispatched_data.length; j++) {
client_name=client_name.concat([{client_name:dispatched_data[j].client_name}]);
branch_name.push(dispatched_data[j].branch_name);
serial.push(dispatched_data[j].router_serial);
data_card_serial.push(dispatched_data[j].data_card_serial);
sim_number.push(dispatched_data[j].sim_number);
if(dispatched_data[j].modem_serial != null){
modem_serial.push(dispatched_data[j].modem_serial);
}else{
modem_serial.push("nodata");
}
idu_serial.push(dispatched_data[j].idu_serial);
ip_address.push({ip_address:dispatched_data[j].ip_address});
installed_date.push({installed_date:dispatched_data[j].installation_date});
notes.push({notes:dispatched_data[j].notes});
ir_report.push({ir_report:dispatched_data[j].ir_report});
}
var data=[],router=[],datacard=[],sim=[],modem=[],idu=[],branch=[],i;
console.log("Modem Serial: "+modem_serial.toString());
console.log("\n\n\nDispatched Data Length ="+dispatched_data.length);
for(i=0;i<modem_serial.length;i++){
console.log("Modem Serial: "+modem_serial[i]);
Modem.findOne({m_serial_no: modem_serial[i]},{_id: 0,__v:0},function (err,m_data) {
//console.log("err: "+err);
if(m_data!=null){
modem=modem.concat(m_data);
}else{
console.log("\n\n\nm_data : "+m_data);
modem=modem.concat({
m_model: 'No data',
m_serial_no: 'No data'
});
}
console.log("\n\n\nFinal Modem : "+JSON.stringify(modem));
});
}
res.end();
});
});
答案 0 :(得分:0)
for
循环是同步的,而findOne
是异步的。 <{1}}的回调可能不会以findOne
被解雇的顺序被触发。
我会使用async.js,尤其是async#mapSeries,因为您似乎正在尝试将一个数组中的每个元素转换为另一个数组,并且您还希望保留该顺序。
findOne