我在房间预订中应该使用什么样的MongoDB模式?

7 浏览
0 Comments

我在房间预订中应该使用什么样的MongoDB模式?

我正在使用Node.js构建一个房间预订系统。目前我有hotelsroomsbookings三个集合。\nrooms是与hotels相关联的,而bookings是与rooms相关联的。\nbooking.js\n

const bookingSchema = new mongoose.Schema({
    room: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'rooms'
    },
    start: Date,
    end: Date
});

\nrooms.js\n

const roomSchema = new mongoose.Schema({
    roomid: String,
    hotel: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'hotel_managers'
    },
    type: String,
    price: Number,
    capacity: Number,
    facilities: [String],
    amenities: [String],
    img: [String]
});

\nhotels.js\n

const hotel_manager_schema = new mongoose.Schema({
    username: {
        type: String,
        required: true,
        unique: true
    },
    password: {
        type: String,
        required: true
    },
    hotelname: {
        type: String,
        required: true
    },
    role: {
        type: String,
        default: 'manager'
    },
    location: {
        type: String,
        required: true
    },
    img:{
        type: String,
        required: true
    }
})

\n注意:这是一个服务提供商终止的系统,所以一个酒店基本上是一个具有自己的凭证的酒店经理。\n我的目标是,当用户发送一个给定日期范围的查询时,我希望返回所有可用的酒店以及在查询日期范围内没有任何预订的酒店房间。\n我对MongoDB还不太了解,所以对于如何实现我想要的功能的任何提示或建议都将非常有帮助。

0
0 Comments

问题的出现原因:用户已经在MongoDB数据库中积累了一些数据,并且希望在bookingSchema中进行查询。他想要根据当前的预订情况返回在新的日期范围内可用的房间,但他不知道如何处理关系型模式。

解决方法:根据已有的booking entries,用户可以使用日期查询来找到指定日期范围内可用的房间。他可以使用Mongoose提供的模型来创建Booking模型,并使用日期查询来实现。用户可以在Mongoose官方文档的这里找到有关如何创建模型的详细信息,以及在这里找到有关如何使用日期进行查询的信息。

0
0 Comments

问题的出现原因是需要设计一个MongoDB的schema用于房间预订,并且需要能够列出指定日期范围内没有任何预订的酒店和房间。解决方法是通过查询与提供的日期范围有重叠的所有预订,并返回它们的房间ID,然后查询排除了从预订返回的房间ID数组的所有房间。另外,可以通过填充Rooms的hotel属性字段来提取酒店的数据。为了提高查询性能,可以删除旧的预订记录或将其归档,并对房间属性字段进行索引,并在获取预订时只选择房间字段。

根据上述解决方法,可以使用以下MongoDB的schema模型架构:

const bookings = await Booking
  .find({
    $or: [
      { start: { $gte: from_date, $lte: to_date } },
      { end: { $gte: from_date, $lte: to_date } },
      { $and: [{ start: { $lte: from_date } }, { end: { $gte: to_date } }] },
    ],
  })
  .select('room');
const roomIds = bookings.map(b => b.room);
const availableRooms = await Room.find({ _id: { $nin: roomIds } });
const availableRooms = await Room
  .find({ _id: { $nin: roomIds } })
  .populate('hotel', 'username password hotelname role location img');

如果遇到返回所有当前预订的问题,即使查询的日期范围与任何预订都不重叠,可以尝试检查代码实现是否有错误,并按照提供的更改进行修改。另外,当预订记录数量增多时,查询的性能会变慢,可以通过定期删除旧的预订记录并对房间属性字段进行索引来改善性能。

0