为什么我的快递应用程序返回一个空数组?

我正在用express和mongodb创build一个CRUD API。 我有一个特定的路线查询我的mongo数据库中的一个集合,并检索符合查询条件的任何文档。 我的程序然后遍历这些文件,并在我的数据库中find另一个集合中的最新交叉条目

exports.findLatestCommitforAllRepos = function(req,res,next){ var githubCommitDataCollection = index.db.collection(githubCommitDataCollectionName); var enabledRepoCollection = index.db.collection(enabledRepoCollectionName); var latestCommits = []; enabledRepoCollection.find({enabled:true}).toArray(function(err,repos) { if (err) { next(err); } if (repos.length === 0 || repos === 'undefined') { res.status(404); res.send("There are no repos being tracked") } else { repos.forEach(function(enabledRepo) { var repo = enabledRepo.repo; var userOrOrg = enabledRepo.userOrOrg; githubCommitDataCollection.find({repo: repo, userOrOrg:userOrOrg}).sort({commitDate: -1}).limit(1).toArray(function(err,commit) { if (commit.length === 0 || repos === 'undefined') { res.send("No commit found for repo " + repo); } // console.log(commit[0]); latestCommits.push(commit[0]); console.log(latestCommits); }); }); res.setHeader('Content-Type', 'application/json'); res.status(200); res.json(latestCommits); res.end(); } }); } 

这导致返回一个空数组。

当需要以串联方式运行任务函数数组时,可以使用asynchronous库,特别是async.waterfall()方法,每个函数都将数组的结果传递给下一个。

考虑下面的例子:

 // Include the async package // Make sure you add "async" to your package.json async = require("async"); exports.findLatestCommitforAllRepos = function(req,res,next){ var latestCommits = []; async.waterfall([ // Load all documents function(callback) { index.db.collection(enabledRepoCollectionName).find({"enabled": true}).toArray(function(err,repos){ if (err) return callback(err); callback(null, repos); }); }, // Get count of documents where price is empty function(reposData, callback) { async.each(reposData, function(enabledRepo, callback) { index.db.collection(githubCommitDataCollectionName) .findOne({repo: enabledRepo.repo, userOrOrg: enabledRepo.userOrOrg}) .sort({commitDate: -1}).limit(1) .exec(function(err, commit) { latestCommits.push(commit); callback(); }); }, callback); } ], function(err, result) { //This function gets called after the three tasks have called their "task callbacks" if (err) return next(err); res.setHeader('Content-Type', 'application/json'); res.status(200); res.json(latestCommits); res.end(); }); }); 

在代码中有一个小的build议,使用.findOne而不是.find

意思是代替

 githubCommitDataCollection.find({repo: repo, userOrOrg:userOrOrg}).sort({commitDate: -1}).limit(1).toArray(function(err,commit) { 

使用

 githubCommitDataCollection.findOne({repo: repo, userOrOrg:userOrOrg}).sort({commitDate: -1}).exec(function(err,commit) { 

它将只返回一个提交,并检查console.log(提交)值来检查你的结果。

或者请检查共享githubCommitDataCollection现有文件