【发布时间】:2012-05-27 12:50:03
【问题描述】:
我是 Node.js 的新手,我遇到了一个错误:
RangeError: 超出最大调用堆栈大小
我无法解决问题,因为其他有关 Node.js 的 stackoverflow 问题中的大多数堆栈问题都涉及数百个回调,但我这里只有 3 个。
首先是获取 (findById),然后是更新,然后是保存操作!
我的代码是:
app.post('/poker/tables/:id/join', function(req, res) {
var id = req.params.id;
models.Table.findById(id, function(err, table) {
if (err) {
console.log(err);
res.send({
message: 'error'
});
return;
}
if (table.players.length >= table.maxPlayers) {
res.send({
message: "error: Can't join ! the Table is full"
});
return;
}
console.log('Table isnt Full');
var BuyIn = table.minBuyIn;
if (req.user.money < table.maxPlayers) {
res.send({
message: "error: Can't join ! Tou have not enough money"
});
return;
}
console.log('User has enought money');
models.User.update({
_id: req.user._id
}, {
$inc: {
money: -BuyIn
}
}, function(err, numAffected) {
if (err) {
console.log(err);
res.send({
message: 'error: Cant update your account'
});
return;
}
console.log('User money updated');
table.players.push({
userId: req.user._id,
username: req.user.username,
chips: BuyIn,
cards: {}
});
table.save(function(err) {
if (err) {
console.log(err);
res.send({
message: 'error'
});
return;
}
console.log('Table Successfully saved with new player!');
res.send({
message: 'success',
table: table
});
});
});
});
});
最后保存操作时出错!
我将 MongoDb 与 mongoose 一起使用,所以 Table 和 User 是我的数据库集合。
这是我第一个使用 Node.js、Express.js 和 MongoDB 的项目,所以我可能在异步代码中犯了很大的错误 :(
编辑:我尝试用更新替换保存:
models.Table.update({
_id: table._id
}, {
'$push': {
players: {
userId: req.user._id,
username: req.user.username,
chips: BuyIn,
cards: {}
}
}
}, function(err, numAffected) {
if (err) {
console.log(err);
res.send({
message: 'error'
});
return;
}
console.log('Table Successfully saved with new player!');
res.send({
message: 'success',
table: table
});
});
但这无济于事,错误仍然来了,我不知道如何调试它:/
【问题讨论】:
-
请将您的答案放在答案部分。
-
并不是说它会导致堆栈大小问题,但这条线肯定看起来不对:
if(req.user.money < table.maxPlayers)。您所做的一切都没有其他问题。 -
您是在多次请求后出现该错误,还是在第一次请求后出现?
标签: node.js mongodb mongoose express