搜尋

首頁  >  問答  >  主體

為什麼 MongoDB 中沒有保存飯店的 Object _id?

如何修復此錯誤? 以下是HotelRoom模組

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const HotelRoomSchema = new Schema({
    name : {
        type : String,
        require : true
    },
    numberofRooms : {
        type : Number,
        require : true
    },
    typeOfBeds : {
        type : String,
        require : true
    },
    noOfBeds : {
        type : Number,
        require : true
    },
    sleepers : {
        type : Number,
        require : true
    },
    view : {
        type : String,
        require : true
    },
    area : {
        type : Number,
        require : true
    },
    price : {
        type : Number,
        require : true
    },
    hotel : {
        type :Schema.Types.ObjectId ,ref:"Hotel",require:true
    }
})

const HotelRoom = mongoose.model("HotelRoom",HotelRoomSchema);

module.exports = HotelRoom;

/////////這是路由

router.route("/:hotelId/addroom").post((req,res) =>{

    let hotelId = req.params.id;
    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);

    const newRoom = new HotelRoom({
 
        name,
        numberofRooms,
        typeOfBeds,
        noOfBeds,
        sleepers,
        view,
        area,
        price,
        hotelId
    })

    newRoom.save().then(()=>{
        res.json("New Room Added")
    }).catch((err)=>{
        console.log(err);
    })
})

//// 這是Postman的值 http://localhost:8070/hotel/6432d331380ef51c5e992af1/addroom

{
  "name": "豪华套房",
  "numberofRooms": 10,
  "typeOfBeds": "大床",
  "noOfBeds": 2,
  "sleepers": 2,
  "view": "海景",
  "area": 60,
  "price": 200
}

這是保存在MongoDB上的內容 _id : ObjectId('643662e1e5b1f15e6720c1be') name : "豪華套房" 房間數量 : 10 typeOfBeds : "大床" 病床數:2 枕木 : 2 view : "海景" 面積:60 價格:200 __v 0

我需要將hotelId儲存到資料庫中

P粉680000555P粉680000555444 天前515

全部回覆(1)我來回復

  • P粉805931281

    P粉8059312812023-09-10 10:21:49

    找到答案 let hotel = req.params.id; 需要修改為

    let hotel = req.params.hotelId;

    回覆
    0
  • 取消回覆