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

为何酒店ObjectId未存入MongoDB?求修复方案

Mongoose关联酒店ID无法存入MongoDB的解决方法

问题根源

你的代码存在两处关键错误,导致关联的酒店ID无法被正确写入数据库:

  • 路由参数获取错误:路由定义的是/:hotelId/addroom,但你在代码里错误使用req.params.id获取参数,这会让hotelId变量的值为undefined。
  • Schema字段名不匹配:HotelRoom Schema中定义的关联字段名为hotel,但创建文档时你传入的是hotelId,Mongoose会自动忽略Schema中未定义的字段,因此该值不会被存入数据库。

修正后的路由代码

router.route("/:hotelId/addroom").post((req,res) =>{
    // 1. 正确获取路由参数中的hotelId
    let hotelId = req.params.hotelId;
    const name = req.body.name;
    const numberofRooms = Number(req.body.numberofRooms);
    const typeOfBeds = req.body.typeOfBeds;
    const noOfBeds = Number(req.body.noOfBeds);
    const sleepers = Number(req.body.sleepers);
    const view = req.body.view;
    const area = Number(req.body.area);
    const price = Number(req.body.price);

    // 可选:验证hotelId是否为有效的MongoDB ObjectId
    if (!mongoose.Types.ObjectId.isValid(hotelId)) {
        return res.status(400).json("Invalid hotel ID");
    }

    const newRoom = new HotelRoom({
        name,
        numberofRooms,
        typeOfBeds,
        noOfBeds,
        sleepers,
        view,
        area,
        price,
        // 2. 匹配Schema中定义的字段名`hotel`
        hotel: hotelId
    })

    newRoom.save().then(()=>{
        res.json("New Room Added")
    }).catch((err)=>{
        console.log(err);
        res.status(500).json("Error adding room: " + err.message);
    })
})

验证结果

修正后重新发送Postman请求,MongoDB中会正确存储hotel字段,对应值为你传入的酒店ObjectId:

_id : ObjectId('643662e1e5b1f15e6720c1be')
name : "Deluxe Suite"
numberofRooms : 10
typeOfBeds : "King"
noOfBeds : 2
sleepers : 2
view : "Ocean View"
area : 60
price : 200
hotel : ObjectId('6432d331380ef51c5e992af1')
__v : 0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 07:07:43