我在房间预订中应该使用什么样的MongoDB模式?
我在房间预订中应该使用什么样的MongoDB模式?
我正在使用Node.js构建一个房间预订系统。目前我有hotels
、rooms
和bookings
三个集合。\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还不太了解,所以对于如何实现我想要的功能的任何提示或建议都将非常有帮助。
问题的出现原因是需要设计一个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');
如果遇到返回所有当前预订的问题,即使查询的日期范围与任何预订都不重叠,可以尝试检查代码实现是否有错误,并按照提供的更改进行修改。另外,当预订记录数量增多时,查询的性能会变慢,可以通过定期删除旧的预订记录并对房间属性字段进行索引来改善性能。