我有这些收藏品:
Sessao:
{
"_id" : ObjectId("5a450a30ca4b001587fcf967"),
"cliente" : ObjectId("5a1407c8099ca208e48170a5"),
"data" : "28/12/2017",
"numero" : "11",
"dadosORS" : ObjectId("5a4507d451c2c614a788c120"),
"dadosSRS" : ObjectId("5a465bcbca4b001587fcf968")
}
registosORS:
{
"_id" : ObjectId("5a450a30ca4b001587fcf966"),
"sessao" : "11",
"outroResponsavel" : "",
"relacao" : "",
"valorIndividualmente" : "1",
"valorInterpessoal" : "1",
"valorSocialmente" : "1",
"valorGlobalmente" : "1",
"email" : "as@uminho.pt",
"data" : "28/12/2017",
"somaValoresOrs" : 4
}
和registosSRS:
{
"_id" : ObjectId("5a465bcbca4b001587fcf968"),
"sessao" : "11",
"valorRelacao" : "7.18",
"valorObjectivo" : "5.06",
"valorAbordagem" : "5.18",
"valorGeral" : "5.37",
"cliente_id" : "5a1407c8099ca208e48170a5",
"email" : "as@uminho.pt",
"somaValoresSrs" : 22.79,
"data" : "29/12/2017"
}
现在,我需要列出给定cliente_id的所有会话,以及ORS和SRS数据。
我在模型中执行功能以列出此信息,但这不起作用。我以为我可以搜索该clienteid的所有会话,然后使用dadosORS和dadosSRS id,我可以创建一个包含这些数据的数组,但是数组在for之外是未定义的。
ClientesDAO.prototype.dadosORSSRSSession = function(clienteid, callback){
var client_id = new ObjectId.ObjectID(clienteid);
this._connection.open(function(err,mongoClient){
mongoClient.collection('sessao', function(err,collection){
collection.find({cliente:client_id}).toArray(function(err,result){
// console.log('result find das sessoes');
// console.log(result);
var ORS_id = [];
var ORS_cliente = [];
var SRS_id = [];
var SRS_cliente = [];
for (var i=0; i<result.length; i++){
ORS_id[i] = new ObjectId.ObjectID(result[i].dadosORS);
mongoClient.collection('registosORS', function(err,collection){
collection.find({_id:ORS_id[i]}).toArray(function(err,result){
ORS_cliente.push(result[0])
})
})
SRS_id[i] = new ObjectId.ObjectID(result[i].dadosSRS);
mongoClient.collection('registosSRS', function(err,collection){
collection.find({_id:SRS_id[i]}).toArray(function(err,result){
SRS_cliente.push(result[0])
})
})
}
console.log('result ORS');
console.log(ORS_cliente);
console.log('result SRS');
console.log(SRS_cliente);
mongoClient.close();
})
})
})
}
答案 0 :(得分:0)
数组在for之外是未定义的,因为它们是异步的,db操作不会阻塞,使用event避免这种情况。
const EventEmitter = require('events');
class MyEmitter extends EventEmitter { }
const myEmitter = new MyEmitter();
myEmitter.on('myEvent', () => {
console.log('result ORS');
console.log(ORS_cliente);
console.log('result SRS');
console.log(SRS_cliente);
})
for (var i=0; i<result.length; i++){
ORS_id[i] = new ObjectId.ObjectID(result[i].dadosORS);
mongoClient.collection('registosORS', function(err,collection){
collection.find({_id:ORS_id[i]}).toArray(function(err,result){
ORS_cliente.push(result[0])
})
})
SRS_id[i] = new ObjectId.ObjectID(result[i].dadosSRS);
mongoClient.collection('registosSRS', function(err,collection){
collection.find({_id:SRS_id[i]}).toArray(function(err,result){
SRS_cliente.push(result[0])
})
})
if (i == result.length-1) {
myEmitter.emit('myEvent');
}
}
有关异步控制的更多信息,建议您查看promise和async / await。
答案 1 :(得分:0)