Search code examples
javascriptnode.jsexpressmongoose

Cannot read properties of undefined (reading 'push') in node js


i'm trying to add roomSchema to a userSchema

this is my code

router.post('/join-room', async (req, res) => {
  const { roomId, userId } = req.body;
  try {
    const user = await User.findById(userId);
    const room = await Room.findById(roomId);
    if (!user || !room) {
      return res.status(404).json({ message: 'User or room not found' });
    }
    user.rooms.push(roomId);
    await user.save();
    res.json({ message: 'User joined room successfully' });
  } catch (error) {
    console.error(error);
  }
});

this my user schema ,i added room model to my userSchema

const UserSchema = new Schema({
  name: String,
  email: {
    type: String,
    unique: true,
    required: true
  },
  password: {
    type: String,
    required: true
  },

  room: { type: Schema.Types.ObjectId, ref: "Room" }
});

this is my json


{
  _id: new ObjectId("6436c40c989d571ad31563a8"),
  name: 'jquery',
  email: '[email protected]',
  password: '$2a$10$fdPk3EzPPZc4SDxGmYnj3usFm9IlU0SNb.Ek4hINXHTfNSAclscxW',
  __v: 0
} {
  _id: new ObjectId("6436bf25f70ece2db5576081"),
  created_date: 2023-04-12T14:24:37.439Z,
  name: 'vue',
  __v: 0
}

this my error

 Cannot read properties of undefined (reading 'push')

please how can i go about this


Solution

  • Your room property is not set to be an array in your schema. To fix that, surround it in [].

    const UserSchema = new Schema({
      name: String,
      email: {
        type: String,
        unique: true,
        required: true
      },
      password: {
        type: String,
        required: true
      },
    
      room: [{ type: Schema.Types.ObjectId, ref: "Room" }] // Here
    });
    

    Your code also is using user.rooms and not user.room, so you'll either need to make the property above plural or make your usage singular.