我的nodejs应用程序中有一个功能。我想从循环中获取一个值。所以我在循环之前实例化一个变量,并从循环中检查值。一旦获得值,我就将其设置为在循环之前声明的变量,问题出在我退出循环后,我的变量将是其原始值,即我在循环中赋予的值
router.get('/gettext', function (req, res) {
var current = "You Finised All";
var times = 0;
MongoClient.connect(url, function (err, db) {
if (err) throw err;
var dbo = db.db("nodekb");
dbo.collection("texts").find().toArray(function (err, result) {
if (err) throw err;
//console.log("Result is \n" + result);
for (let value of result) {
if (!(value.readBy.includes(req.user._id.toString()))) {
console.log("userId is: " + req.user._id);
//Check if the user and text exist in Repeat collection parseInt(value.no, 10)
dbo.collection("repeat").find({ uid: req.user._id.toString(), textNo: parseInt(value.no, 10) }).toArray(function (err, doc) //find if a value exists
{
console.log("Doc is:");
console.log(doc);
if (doc.length > 0) //if it does
{
console.log("This User exists in this metin. UserId: " + req.user._id.toString() + " and from database: " + doc[0].uid + " With timesRead " + doc[0].timesRead);
times = doc[0].timesRead;
}
else // if it does not
{
var toBeSent = {
uid: req.user._id.toString(),
textNo: value.no,
timesRead: 0
}
console.log(toBeSent);
MongoClient.connect(url, function (err, db) {
if (err) throw err;
// insert document to 'repeat' collection using insertOne
db.collection("repeat").insertOne(toBeSent, function (err, res) {
if (err) throw err;
console.log("Document inserted");
// close the connection to db when you are done with it
db.close();
});
});
}
});
console.log('Value is : ');
console.log(value); //this value print shows ''
current = value;
break;
}
};
current.noOfTimes = times;
console.log('current.noOfTimes: ' + current.noOfTimes);
res.send(current);
console.log(req.user._id);
db.close();
});
});
})
我期望变量'times'保持不变,即它离开循环时的状态,但是我得到的却是0。