为什么 MongoDB 中没有保存酒店的 Object _id?
P粉680000555
P粉680000555 2023-09-09 17:54:13
0
1
512

如何修复此错误? 以下是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粉680000555
P粉680000555

全部回复(1)
P粉805931281

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

let hotel = req.params.hotelId;
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板