即使我没有使用递归,最大调用堆栈大小也超出了错误

在我的节点应用程序中,我有一条导致最大调用堆栈大小错误的路由。当我尝试将用户从mongodb推入数组时,会发生这种情况。这是导致错误的路由:

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
  }
}

用户:

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
  }
});

我怎样才能解决这个问题?

评论
  • 头碰头
    头碰头 回复

    您可能错误地两次导入了相同的js文件。这可能是发生这种情况的原因之一。