我是 Express js 和 Node js 的新手。我想知道是否可以这样做。
第一件事是我试图获取 1 个查询的计数。
第二次我查询集合登录。循环它并格式化并使用 ids 获取名称值。
我在 count1 上未定义,并且我看到它在 json 响应中被省略。
如何在查询之外传递查询返回?
router.post('/logmein', function(req, res, next) {
var email = req.param('email');
var password = req.param('password');
var count1;
MongoClient.connect(MongoUrl, function(err, db) {
if (err) return;
db.collection('users').count({email: email,password: md5(password)}, function(err, count) {
count1 = count;
});
db.collection('login').find({email: email,password: md5(password)}).toArray(function(err, results){
console.log(results); // output all records
});
//use results
/*
foreach each results format with other info
var new_array;
*/
res.json({"success": true,"count":count1,new_array: new_array});
});
});
最佳答案
异步问题,你得多看看。使用async module然后您将能够并行触发查询。最后,您将在最终回调中得到结果。此代码片段将解决您的问题:
var async = require('async');
router.post('/logmein', function (req, res, next) {
var email = req.param('email');
var password = req.param('password');
var retResults;
var count1;
MongoClient.connect(MongoUrl, function (err, db) {
if (err) return;
async.parallel([
function(callback){
db.collection('users').count({ email: email, password: md5(password) }, function (err, count) {
return callback(err, count);
});
},
function(callback){
db.collection('login').find({ email: email, password: md5(password) }).toArray(function (err, results) {
return callback(err, results);
});
}
], function(err, results) {
if (err) {
// @todo: handle the error
}
count1 = results[0];
retResults = results[1];
//use results
/*
foreach each results format with other info
var new_array;
*/
res.json({ "success": true, "count": count1, new_array: new_array });
};
});
});
关于node.js - Express js 使用 mongodb 中的值到查询之外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39999171/