【发布时间】:2017-03-19 09:05:38
【问题描述】:
今天我的问题实际上是关于由于循环无法正常工作而发生的问题,但无论如何,如果我在设计方面遇到问题,我对想法持开放态度。
app.post('/admin/earning/:multiplier', function (req, res) {
var multiplier = req.params.multiplier;
var now = new Date();
var List=[];
var dailySaving;
// Getting the investors emails(key) from the collection.
db.getInvestorsFromValidatedInvests(function(err,result){
if(err){console.log(err);}
console.log(result);
List = result;
console.log('Inside the List scope'+List[0]);
for(var i=0;i<List.length;i++){
db.returnTotalInvestingfromValidatedInvests(List[i],function(err,rst){
if(err){console.log(err);}
console.log(rst);
var dailySaving = ((rst*multiplier)/100);
console.log('Daily Savings which is going to be added is that : ' +dailySaving);
console.log(List[i]);
db.multiplyInvestAndAddSavings(List[i],dailySaving,function(err,rest){
if(err){console.log(err);}
console.log(rest);
});
});
}
});
res.json('Going to be Prepared...');
});
在这里,我将与您分享这些数据库功能中的每一个:
第一个函数从 db 获取所有者的电子邮件并返回一个数组,然后,我想对这个数组的每个元素进行一些操作,我决定使用 for 循环,但它不能正常工作。
Db.prototype.getInvestorsFromValidatedInvests = function(callback){
MongoClient.connect("mongodb://xxxxxxx:xxxxxxx@ds9999.mlab.com:99986/xxxxxx", function (err, db) {
if (err) { return console.dir(err); }
db.collection('validatedInvests').distinct("owner",function(err,result){
if(err){console.log(err); callback(err,null);}
callback(null,result);
});
db.close();
});
}
Db.prototype.returnTotalInvestingfromValidatedInvests = function(owner,callback){
MongoClient.connect("mongodb://xxxxxxxx:xxxxxxx@ds09999.mlab.com:9996/aslanservices", function (err, db) {
if (err) { return console.dir(err); }
db.collection('validatedInvests').find({"owner":owner}).toArray(function(err,result){
var sum=0;
if(err){console.log(err); callback(err,null);}
for(var j=0;j<result.length;j++){
sum+=parseInt(result[j].amount);
}
callback(null,sum);
});
db.close();
});
}
Db.prototype.multiplyInvestAndAddSavings = function(owner,amount,callback){
MongoClient.connect("mongodb://xxxxxx:xxxxxxx@ds99996.mlab.com:39996/aslanservices", function (err, db) {
if (err) { return console.dir(err); }
console.log('Db talking amount is'+amount);
db.collection('investClients').updateOne({"email":owner},
{
$inc : {
"savingsAccount" : +amount
},
},
{
upsert : true
}
,function(err,result){
if(err){callback(err,null);}
callback(null,result);
});
db.close();
});
}
输出是:
在列表范围内> 让我们说 blablabla@gmail.com
220
要添加的每日储蓄是:8.8
未定义
150
要添加的每日储蓄是:6
未定义
Db 通话量为 8.8
Db 通话量为 6
预期的输出是:
220
要添加的每日储蓄是:8.8
blablabla@gmail.com
Db 通话量为 8.8
150
要添加的每日储蓄是:6
secondblablabla@gmail.com
Db 通话量为 6
【问题讨论】:
-
循环“无法正常工作”:尽管有代码,请更准确:它的行为如何/应该如何工作?
-
请提供minimal reproducible example,而不是代码转储和模糊描述。
-
好的,请稍等,我将添加预期和正常输出
标签: node.js mongodb loops callback nested