有人可以通过解决方案启发我以下情况吗?
我有一个用nodeJS express框架编写的日志应用程序,并使用MongoDB集合。我设法从集合中获取结果,但我想迭代结果,根据第一个查询中的引用ID查询另一个集合,并将更多值附加到初始结果,然后将响应发送给客户端。
我将粘贴下面我现在编码的内容,但我无法让它工作。我做错了或者我想要的逻辑不正确。
除了理论和事实,我不能在异步JS函数之外使用结果,请帮助我。
提前致谢!
CODE:
exports.findLogs = function(req, res) {
var params = req.body;
var query = req.query;
var coll = params.section;
if (coll === undefined) {
coll = 'traces';
}
db.collection(coll, function(err, collection) {
collection.count(function(err, count) {
var criteria = {
'limit': limit,
'skip': skip,
'sort': [[options.sortname, options.sortorder]]
}
collection.find({}, criteria).toArray(function(err, items) {
Object.keys(items).forEach(function(logIndex) {
var trace = items[logIndex];
var crit = {
'find': {LogId: trace.LogId},
'projection': {},
'limit': 1
}
// Get entry based on Criteria from `log` table
findOneBy(crit, 'log', function(err, log) {
if (log.length !== 1) {
// no reference found
} else {
// Appending here to log DOES NOT stick as expected
trace.ComputerName = log.ComputerName;
trace.ComputerIP = log.ComputerIP;
trace.LastSeen = log.LastSeen;
trace.TestVar = 'test1234';
}
});
// Appending here to trace works as expected
trace.Actions = 'MyAction';
});
results['total'] = count;
results['results'] = items.length;
results['rows'] = items;
res.send(results);
});
});
});
}
function findOneBy(criteria, coll, callback) {
var cFind = criteria.find;
var cProj = criteria.projection;
db.collection(coll, function(err, collection) {
if (err) return callback(err);
else return collection.find(cFind, cProj).toArray(callback);
});
}
答案 0 :(得分:2)
您的函数findOneBy
是异步的。当您的代码循环遍历items
中存储的结果数组时,每个代码都会触发异步查找。
然而,在所有这些返回之前,您将通过`res.send(结果)将结果发送给客户端。因此,当数据返回到Node.JS应用程序时,之后结果已经发送。
有几种方法可以解决这个问题,但我建议你考虑更像这样的逻辑(伪代码,因为我没有镜像数据的数据库):
collection.find({}, criteria).toArray(function(err, items) {
var allLogIds = [];
var logIdsByUse = {};
Object.keys(items).forEach(function(logIndex) {
// here, we'll first bit a list of all LogIds
var trace = items[logIndex];
allLogIds.push(trace.LogId);
// now build a index of logId and a list of dependent objects
logIdsByUse[trace.LogId] = [] || logIdsByUse[trace.LogId];
logIdsByUse[trace.LogId].push(trace);
});
// now that the LogIds are all gathered, we'll do a search for all of them
// at once.
// *** You should make certain that the LogId field is indexed or this will
// *** never perform adequately in any situation
db.collection("log", function(err, collection) {
if (err) { /* do something with the error, maybe 500 error */ }
else {
collection.find({ LogId: { $in : allLogIds}})
.toArray(function(err, logs) {
logs.forEach(function(log) {
// grab the LogId,
// get the array of traces that use the LogId
// from the logIdsByUse[LogId]
// loop through that array, and do the fix up that you
// want
});
// now, you may send the results
results['total'] = count;
results['results'] = items.length;
results['rows'] = items;
res.send(results);
});
});
});
您还可以查看使用Node.JS的其中一个异步库,但它不会显着改变您需要做的事情。
答案 1 :(得分:0)
callMe(function(initialResults) {
//iterate over the array or object
//take your new results and combine them with the initial Results,
//To be done differently depending if you have an array, object, or array of objects.
res.send(newResults)
};
function callMe(callback) {
//query your database and get your first results
callback(initialResults)
}
这有帮助吗?如果没有解释你会得到什么样的错误或结果