You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MERN预订项目中TypeError: Cannot read 'some' of undefined问题排查

预订应用日期判断报错处理

问题根源

原错误Uncaught TypeError: Cannot read properties of undefined (reading 'some')是因为roomNumber.unavailableDates为undefined,无法调用数组方法some。添加可选链后出现新错误,核心原因是MongoDB模型定义错误:unavailableDates被定义为单个Date类型,但实际需要存储多个不可用日期,应该是数组类型。

修正步骤

  1. 修正Room.js模型定义
    将unavailableDates的类型改为数组形式,确保后端能正确存储多个日期:
const RoomSchema= new mongoose.Schema({
    // 其他字段省略
    roomNumbers:[{number: Number ,unavailableDates: [{type: Date}] } ],
},{timestamps:true})
  1. 优化Reserve.jsx的isAvailable函数
    增加对unavailableDates不存在或为空的判断,避免逻辑错误:
const isAvailable = (roomNumber) => {
    // 若没有不可用日期,直接返回可用
    if (!roomNumber?.unavailableDates || roomNumber.unavailableDates.length === 0) {
        return true;
    }
    const isFound = roomNumber.unavailableDates.some(date =>
      alldates.includes(new Date(date.getTime()))
    );
    return !isFound;
};

说明

模型中unavailableDates定义为单个Date时,后端返回的不是数组,前端调用some方法会出错;即使加了可选链,undefined.some返回undefined,取反后逻辑不符合预期,因此出现新错误。改成数组类型后,后端返回正确的数组结构,前端就能正常执行日期重叠判断。

内容的提问来源于stack exchange,提问作者Unknown

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 23:55:20