A custom Mongoose schema type for handling timezone-aware dates using the @open-rlb/date-tz library.
- Stores date and time as a structured object with
timestampandtimezone. - Supports casting plain objects to
DateTzinstances. - Easily integrates into Mongoose schemas.
- Type-safe with
IDateTzinterface.
npm install @open-rlb/date-tzAdd the custom schema type file (e.g. date-tz.schema.ts) to your project.
This custom schema type lets you store timezone-aware date objects in MongoDB using Mongoose. It wraps around the DateTz class from the @open-rlb/date-tz package and ensures your application consistently handles date/times across timezones.
The expected shape is:
{
timestamp: number; // Unix timestamp in milliseconds
timezone: string; // IANA timezone string (e.g., "Europe/Rome")
}Ensure DateTzSchema is registered once in your application:
import mongoose from "mongoose";
import { DateTzSchema } from "./date-tz.schema"; // adjust path as needed
mongoose.Schema.Types['DateTzSchema'] = DateTzSchema;import mongoose from "mongoose";
const BookingSchema = new mongoose.Schema({
pickupDate: {
type: mongoose.Schema.Types['DateTzSchema'],
required: true,
},
});import { DateTz } from "@open-rlb/date-tz";
const booking = new BookingModel({
pickupDate: new DateTz(Date.now(), "Europe/Rome"),
});
await booking.save();{
"pickupDate": {
"timestamp": 1750506300000,
"timezone": "Europe/Rome"
}
}This schema type will automatically cast objects that match { timestamp: number, timezone: string } into DateTz instances.
const raw = {
timestamp: 1750506300000,
timezone: "Europe/Rome"
};
const casted = new DateTzSchema('pickupDate', {}).cast(raw);
console.log(casted instanceof DateTz); // true- The
cast()method currently supports:DateTzinstances (returned as-is)- Plain objects with
timestampandtimezonekeys
- String parsing is commented out — you can enable it if you need to parse formatted strings.
MIT