【发布时间】:2019-09-25 11:04:27
【问题描述】:
我创建了一个 For 循环,它为我的数据库中的用户分配值。 我的代码包括:-
一个名为 Output 的数组,类似这样;
{['Number': '907384719', 'amount': 23],
['Number': '907118281', 'amount': 50]}
然后我创建了一个 for 循环,从 output 数组中提取 number 和 amount 值;
var getLength = output.length;
for (var i = 0; i < output.length; i++) {
numbers = output[i].number;
amount1 = output[i].amount;
}
在我的应用程序中,我对用户的数据集合进行了查询,以提取用户的 ID,其编号列在上述 输出 数组中。
var query = { number: numbers };
db.collection("accounts").find(query).toArray(function(err, result, from, to) {
if (err) throw err;
for (i = 0; i < result.length; i++) {
id = result[i]._id;
获得用户 ID 后,我想通过 输出数组中列出的数量值;
balance.findOneAndUpdate({
userId: getObjectId(id)
}, {
$inc: {
balance: parseInt(amount1)
}
}, async function(err, res) {
if (err) {
return callback(err)
} else {
callback(null, res.value.balance)
}
});
编写此代码后我遇到了问题。此脚本会增加所选用户的余额,但会增加错误的 amount 值。
for 循环仅使用输出数组中的第一个“amount”值增加余额。例如,通过使用上面的数组,脚本将每个用户的余额增加 23 个点。
我尝试了很多东西,但似乎有什么东西阻塞了我的 For 循环。这是完整的代码,我包含了一些cmets来解释更多;
exports.findUser = function(newData, e, callback) {
// get the number and the amoount attached
var output = {
['Number': '907384719', 'amount': 23],
['Number': '907118281', 'amount': 50]
}
var getLength = output.length;
for (var i = 0; i < output.length; i++) {
numbers = output[i].number;
amount1 = output[i].amount;
//console.log(numbers); These two consoles seem to output the right data
//console.log(amount1);
var query = {
number: numbers
};
db.collection("accounts").find(query).toArray(function(err, result, from, to) {
if (err) throw err;
for (i = 0; i < result.length; i++) {
// gets the IDs of the users with their numbers are in the "output array"
id = result[i]._id;
//var amount = 500;
balance.findOneAndUpdate({
userId: getObjectId(id)
}, {
$inc: {
balance: parseInt(amount1) // only increments with 23 points
}
}, async function(err, res) {
if (err) {
return callback(err)
} else {
callback(null, res.value.balance)
}
});
//console.log(id);
//console.log(numbers); outputs only he first number
//console.log(amount1); outputs only the first amount "23"
}
});
}
}
我的脚本正在获取正确的帐户来增加点数,但它仅随着数组中的第一个“金额”值而增加。因此,请帮助我了解如何使用 output 数组中的每个余额来增加每个余额。
【问题讨论】:
标签: arrays node.js string mongodb for-loop