@everytravel/shared
Version:
A comprehensive shared package for Everytravel containing Mongoose models and CRUD operations for hotel booking, user management, and transaction handling. Updated with improved model syntax and enhanced error handling.
38 lines (36 loc) • 1.88 kB
JavaScript
import mongoose from "mongoose";
const { Schema } = mongoose;
import { isNonEmptyString, isNonNegativeNumber, trimIfString, arrayOfStringsSanitizer } from '../validation/index.js';
/**
* Discount model for hotel properties.
*
* @typedef {Object} Discount
* @property {String} code - Discount code.
* @property {String} description - Discount description.
* @property {Number} percentage - Discount percentage.
* @property {Number} amountOff - Discount amount.
* @property {Date} validFrom - Discount valid from date.
* @property {Date} validTo - Discount valid to date.
* @property {Number} usageLimit - Discount usage limit.
* @property {ObjectId[]} usedBy - References to User documents.
* @property {String[]} applicableTo - Array of applicable models (e.g., "Hotel", "Ride", "Suite").
*/
const DiscountSchema = new Schema({
code: { type: String, set: trimIfString, index: true },
description: { type: String, set: trimIfString },
percentage: { type: Number, min: 0, max: 100 },
amountOff: { type: Number, min: 0 },
validFrom: Date,
validTo: { type: Date, validate: { validator(value) { return !value || !this.validFrom || value >= this.validFrom; }, message: 'validTo must be after validFrom' } },
usageLimit: { type: Number, min: 0 },
usedBy: [{ type: Schema.Types.ObjectId, ref: 'User' }],
applicableTo: { type: [String], set: arrayOfStringsSanitizer }, // e.g. ["Hotel", "Ride", "Suite"]
});
// Indexes to optimize lookups and validity windows
// Note: single-field index already defined on `code` at field level
DiscountSchema.index({ validFrom: 1 });
DiscountSchema.index({ validTo: 1 });
DiscountSchema.index({ usedBy: 1 }); // multikey
DiscountSchema.index({ applicableTo: 1 }); // multikey
const Discount = mongoose.model('Discount', DiscountSchema);
export default Discount;