1
我遇到了一些問題,我的convertKey函數,我懷疑這是由於範圍問題。基本上,我嘗試從我的mongo數據庫中檢索一條記錄並將其存儲在count變量中,但是當我嘗試返回它時,我得到「undefined」。令人驚訝的是,console.log(nameSearch + count)
工程,而return nameSearch + count
沒有。如果有人能幫助我,我真的很感激!JavaScript的問題(node.js + mongo.db)
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;
});
});
}
});
};
}
謝謝!只需一次快速跟進:我嘗試添加一個回調函數,並將其稱爲此類函數,但它不起作用。你知道我要去哪裏嗎this.key = convertKey(this.name,function(text){ return text; }); – 2013-03-18 07:19:25
@DanTang我認爲你需要閱讀[Continuation-passing style](http://en.wikipedia.org/wiki/Continuation-passing_style),這裏有一篇很好的文章(http:// matt。 might.net/articles/by-example-continuation-passing-style/)。基本上,您需要包含所有依賴該回調函數中的「text」值的邏輯。這與您在傳遞給'db.studentsList.find'的回調中所做的相同。 – 2013-03-18 19:02:23
啊,明白了,謝謝你的鏈接! – 2013-03-19 05:34:37