我的convertKey函数遇到一些问题,我怀疑这是由于范围问题引起的。基本上,我尝试从mongo数据库中检索一条记录并将其存储在count变量中,但是当我尝试返回它时,却显示为“ undefined”。令人惊讶的是,console.log(nameSearch + count)
有效,而return nameSearch + count
无效。如果有人可以帮助我,我将不胜感激!
var dbUrl = "kidstartnow",
collections = ["students", "studentsList"];
var db = require("mongojs").connect(dbUrl, collections);
function Student(name, src) {
this.name = name.toLowerCase();
//this function does not work
this.key = convertKey(this.name);
this.src = src;
this.pointsTotal = 0;
//inserts student into database
var student = {name: this.name, key: this.key, pointsTotal: this.pointsTotal,
src: this.src
};
db.students.insert(student);
//converts name to a key by stripping white space and adding a number behind and ensures keys are unique
//concatenates names together to form namesearch, and checks if entry exists in studentsList
function convertKey(name) {
var nameSearch = name.replace(/\s/g, ''),
count = 1;
db.studentsList.find({name: nameSearch}, function(err, student) {
//if nameSearch does not exist in studentsList, create entry and sets count to 1
if(err || !student.length) {
db.studentsList.insert({name: nameSearch, count: 1});
count = 1;
return nameSearch + count;
}
//if entry does exist, increments count by 1
else {
db.studentsList.update({name: nameSearch}, {$inc: {count: 1}}, function(err) {
if(err) {
console.log("Error incrementing records");
}
db.studentsList.find({name: nameSearch}, function(err, student) {
count = student[0].count;
//this works
console.log(nameSearch + count)
//but this doesn't
return nameSearch + count;
});
});
}
});
};
}
最佳答案
您是从回调返回到db.studentsList.find
,而不是从convertKey
函数返回。
如果希望从db.studentsList.find
内部返回值,则需要提供对convertKey
的回调,或者可能使用Promise库将convertKey
设置为延迟/将来。否则,您的函数将在等待嵌套异步函数完成时立即返回。
回调使您可以传递所需的结果(例如callback(nameSearch + count)
)
编辑
每当我对函数的返回值有疑问时,都将大括号与注释匹配:
function convertKey(name) {
var nameSearch = name.replace(/\s/g, ''),
count = 1;
db.studentsList.find({name: nameSearch}, function(err, student) {
//if nameSearch does not exist in studentsList, create entry and sets count to 1
if(err || !student.length) {
db.studentsList.insert({name: nameSearch, count: 1});
count = 1;
return nameSearch + count;
} else {
db.studentsList.update({name: nameSearch}, {$inc: {count: 1}}, function(err) {
// ...
db.studentsList.find({name: nameSearch}, function(err, student) {
// ...
return nameSearch + count;
}); // end db.studentsList.find
}); // end db.studentsList.update
} // end else
}); // end db.studentsList.find
/**
* Notice, no return value here...
*/
}; // end convertKey