Node.js 将更多属性附加到从NodeJS(express)和#x2B;MongoDB-模拟SQL连接

Node.js 将更多属性附加到从NodeJS(express)和#x2B;MongoDB-模拟SQL连接,node.js,mongodb,node-mongodb-native,Node.js,Mongodb,Node Mongodb Native,有人能给我一个解决以下情况的方法吗 我有一个用nodeJS express框架编写并使用MongoDB集合的日志应用程序。我设法从一个集合中获取结果,但我希望对结果进行迭代,根据第一次查询中的引用ID查询另一个集合,并向初始结果附加更多值,然后将响应发送给客户端 我将把我现在编写的代码粘贴到下面,但我无法让它工作。我不是做错了,就是我想要的逻辑不正确 除了理论和事实之外,请帮助我,我不能在异步JS函数之外使用结果 提前谢谢 代码: 这有用吗?如果没有,请解释您得到的错误或结果是什么您的函数fin

有人能给我一个解决以下情况的方法吗

我有一个用nodeJS express框架编写并使用MongoDB集合的日志应用程序。我设法从一个集合中获取结果,但我希望对结果进行迭代,根据第一次查询中的引用ID查询另一个集合,并向初始结果附加更多值,然后将响应发送给客户端

我将把我现在编写的代码粘贴到下面,但我无法让它工作。我不是做错了,就是我想要的逻辑不正确

除了理论和事实之外,请帮助我,我不能在异步JS函数之外使用结果

提前谢谢

代码:


这有用吗?如果没有,请解释您得到的错误或结果是什么

您的函数
findOneBy
是异步的。当代码在存储在
项中的结果数组中循环时,每个结果都会触发异步查找

但是,在所有这些返回之前,您将通过`res.send(results)向客户端发送结果。因此,当数据返回到Node.JS应用程序时,结果已经发送之后

有一些方法可以处理这个问题,但是我建议你把逻辑考虑得更像这个(伪代码,因为我没有数据库镜像你的数据):


您也可以考虑为Node.JS使用一个异步库,但它不会显著改变您需要做的事情。

我想我正是按照您的建议做的,对吗?我有一个问题,我合并了结果,我认为问题是因为我在一个异步函数中这样做,但我无法通过将
log
对象记录在该函数中,来确定如何使findOneBy中找到的结果粘在log对象上,好像我需要它。我想我的代码完全符合你的建议。在异步函数运行后,我无法使findOneBy的结果(单个)保持在“log”对象上,因为如果我输出到console,我会看到我的对象看起来正是我所需要的。因此,我对您的回答的问题是://获取新结果,并将它们与初始结果相结合可以怎么做?谢谢你冗长的解释和回复代码。这正是我所需要的,它的工作正如预期。而且,我现在更清楚地知道,这个逻辑应该是怎样的。你就是那个人!祝你一周愉快!
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);
    });
}
     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)
     }
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);               
                });
    });        

});