Node.js Mongoose将findOne()结果赋值给变量
我有一个功能:Node.js Mongoose将findOne()结果赋值给变量,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我有一个功能: function RetrieveCountryCode(countryName, callback) { Country.find({ name: countryName }, function(err, country) { if (err) { callback(err, null); } else { callback(null, country.code); } }); } 我是这样使用它的: //find a
function RetrieveCountryCode(countryName, callback) {
Country.find({ name: countryName }, function(err, country) {
if (err) {
callback(err, null);
} else {
callback(null, country.code);
}
});
}
我是这样使用它的:
//find a country code of a given country by user
var userCountryCode = null;
RetrieveCountryCode(country, function(err, countryCode) {
if (err) {
console.log(err);
}
userCountryCode = countryCode;
});
console.log("COUNTRY CODE");
console.log(userCountryCode);
*给定给函数的参数'country'来自html表单,它传递正确,我检查了它
我在控制台中仍然得到相同的响应:国家代码null。我做错了什么…?正如Suleyman在评论中所说,这是由于节点的异步性质。代码的流程与您期望的不同。互联网上有很多关于节点异步性质的教程,我建议您了解它们并进行实验,因为一开始并不十分直观 因此,
console.log(userCountyCode)
是在RetrieveCountryCode()
完成其工作之前执行的
解决方案是将console.log(userCountyCode)
放在回调中
例如,如果我的集合包含:
> db.countries.find()
{ "_id" : ObjectId("5dc4fcee86c118c901a7de35"), "name" : "Australia", "code" : "61", "__v" : 0 }
使用已修改的代码版本:
var userCountryCode = null;
var country = 'Australia';
mongoose.connect(url, opts)
function RetrieveCountryCode(countryName, callback) {
Country.findOne({ name: countryName }, function(err, country) {
if (err) {
callback(err, null);
} else {
callback(null, country.code);
}
});
}
RetrieveCountryCode(country, function(err, countryCode) {
if (err) {
console.log(err);
}
userCountryCode = countryCode;
console.log("COUNTRY CODE");
console.log(userCountryCode);
});
console.log('xxx');
请注意,我根本没有更改RetrieveCountryCode
函数的定义。我刚刚更改了它的调用方式,并将控制台.log
移动到回调中。我将console.log('xxx')
放在它的位置
运行此代码将输出:
xxx
COUNTRY CODE
61
请注意,xxx
是在国家代码之前打印的,因为它是在回调打印查询结果之前执行的
总之,您的代码总是打印null
,因为:
注意:我将代码中的
find()
更改为findOne()
。我相信find()
是您的输入错误。RetrieveCountryCode是一个异步函数,因此javascript调用RetrieveCountryCode,但不等待它并继续执行代码,因此userCountryCode中的值为空。您需要在RetrieveCountryCode调用中记录并使用它,但我希望稍后在代码中使用countryCode变量-将其作为参数传递给模型创建。我该如何做到这一点?我是否应该锁定代码,直到我从DB=获得该值,直到countryCode不再为null?怎么做?你不能那样做。请看一下这些:在我阅读这些链接之前:那么,如果FindOne的结果不能被分配到,我该怎么办呢?在将两个答案(您的答案和上面的答案)结合在一起之后,我只是将逻辑移到了里面(在应用程序中,它不仅仅是一个控制台日志,而是一个完整的用户创建),并且必须嵌套两个FindOne()函数。事实上,find()是一个输入错误,但不仅在这里,在我的代码中也是如此。。。非常感谢。