Reputation: 33
In my node application, I have a route that is causing a maximum call stack size error. This happens when I try to push a user from mongodb into an array. Here is the route that is causing the error:
router.get('/join', auth, async (req, res) => {
try {
const user = await User.findById(req.user.id).populate('room');
const rooms = await Room.find({ full: false }).populate('players.user');
let room;
if (rooms.length <= 0 || !rooms) {
room = new Room();
} else {
rooms.sort((a, b) => (a.playerCount > b.playerCount ? -1 : 1));
room = rooms[0];
}
user.room = room;
await user.save();
if (room.players.length == room.playerCount) {
room.players.push({ user });
// room.playerCount += 1;
}
await room.save();
res.json(room);
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error');
}
});
The error only occurs when I keep the line: room.players.push({ user });
. Here is the code for the room and user schemas:
const RoomSchema = new mongoose.Schema({
players: [
{
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
hand: {
type: Array,
default: []
}
}
],
playerCount: {
type: Number,
default: 0
},
full: {
type: Boolean,
default: false
}
}
User:
const UserSchema = new mongoose.Schema({
username: {
type: String,
required: true
},
password: {
type: String,
required: true
},
earning: {
type: Number,
default: 50000
},
wins: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
],
losses: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
],
room: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Room'
},
date: {
type: Date,
default: Date.now
}
});
How can I fix this?
Upvotes: 1
Views: 69
Reputation: 636
It is possible that you have imported the same js file twice, by mistake. It would be possibly one of the reasons this could happen.
Upvotes: 1