gpt4 book ai didi

javascript - javascript 的范围问题(node.js + mongodb)

转载 作者:太空宇宙 更新时间:2023-11-04 01:12:26 25 4
gpt4 key购买 nike

我的 ConvertKey 函数遇到一些问题,我怀疑这是由于范围问题造成的。基本上,我尝试从 mongo 数据库中检索记录并将其存储在计数变量中,但是当我尝试返回它时,我得到“未定义”。令人惊讶的是,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 成为延迟/ future 。否则,您的函数将在等待嵌套异步函数完成时立即返回。

回调允许您传递您正在查找的结果(例如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

关于javascript - javascript 的范围问题(node.js + mongodb),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15470383/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com