我遇到了一些我的convertKey函数的问题,我怀疑这是由于范围问题。基本上,我尝试从我的mongo数据库中检索记录并将其存储在count变量中,但是当我尝试返回它时,我得到“未定义”。令人惊讶的是,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;
});
});
}
});
};
}
答案 0 :(得分:1)
您将从回调返回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