我遇到了问题。我无法为var设置响应变量。 我正在使用node.js + mongo.db 这就是我的代码的外观:
function updateTradeLink(sid, link) {
if(!g_Mongoconnected)
return 0;
var TradeUrl = '';
existUser(sid, function(exist){
if(exist)
{
userListDB.find({'steamid':sid}).toArray(function(err, list) {
TradeUrl = list.trade-link;
});
helper.log(TradeUrl);
var PartnerURL = TradeUrl.substring(0,60);
var linkU = link.substring(0,60);
helper.log(linkU);
helper.log(PartnerURL);
if (PartnerURL == linkU)
{
userListDB.update({steamid: sid}, {steamid: sid, tradelink: link});
}
else
{
helper.log('detected tried to change partner!');
}
}
else userListDB.insert({steamid: sid, tradelink: link}, {w:1}, function(err)
{
if(err)
{
helper.log('Error inserting tradelink', 485, err);
}
});
});
}
我没有给出任何回复,我的数据库显示:http://prntscr.com/7v0yx8
答案 0 :(得分:0)
find()是异步的。因此,更新应该在find()的回调中。以下是修订后的代码:
function updateTradeLink(sid, link) {
if (!g_Mongoconnected) {
return 0;
}
var TradeUrl = '';
existUser(sid, function(exist) {
if (exist) {
userListDB.find({'steamid': sid}).toArray(function(err, list) {
TradeUrl = list['trade-link'];
helper.log(TradeUrl);
var PartnerURL = TradeUrl.substring(0, 60);
var linkU = link.substring(0, 60);
helper.log(linkU);
helper.log(PartnerURL);
if (PartnerURL == linkU) {
userListDB.update({steamid: sid}, {steamid: sid, tradelink: link});
}
else {
helper.log('detected tried to change partner!');
}
});
} else {
userListDB.insert({steamid: sid, tradelink: link}, {w: 1}, function(err) {
if (err) {
helper.log('Error inserting tradelink', 485, err);
}
});
}
});
}
注意:在执行TradeUrl.substring(0,60)之前应检查TradeUrl。另外:find()返回的列表实际上是一个数组,因此list ['trade-link']可能不是正确的做法。