ecomm/__tests__/mongoose/Schema.test.ts

75 lines
2.2 KiB
TypeScript
Raw Normal View History

2023-06-13 13:10:17 +00:00
import mongoose, { Schema, Document } from 'mongoose';
export interface IUser extends Document {
email: string;
password: string;
address: string;
createdAt: Date;
updatedAt: Date;
}
export interface IProduct extends Document {
name: string;
description: string;
price: number;
userId: string;
createdAt: Date;
updatedAt: Date;
}
export interface ICart extends Document {
userId: string;
products: { [itemId: string]: number };
createdAt: Date;
updatedAt: Date;
}
export interface IOrder extends Document {
userId: string;
products: { [itemId: string]: number };
emailSent: boolean;
createdAt: Date;
updatedAt: Date;
}
const UserSchema: Schema = new Schema({
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
address: { type: String, required: true },
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date, default: Date.now },
});
const ProductSchema: Schema = new Schema({
name: { type: String, required: true },
description: { type: String, required: true },
price: { type: Number, required: true },
userId: { type: Schema.Types.ObjectId, ref: 'User', required: true },
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date, default: Date.now },
});
const CartSchema: Schema = new Schema({
userId: { type: Schema.Types.ObjectId, ref: 'User', required: true, unique: true },
products: { type: Schema.Types.Mixed, default: {} },
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date, default: Date.now },
});
const OrderSchema: Schema = new Schema({
userId: { type: Schema.Types.ObjectId, ref: 'User', required: true },
products: { type: Schema.Types.Mixed, default: {} },
emailSent: { type: Boolean, default: false },
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date, default: Date.now },
});
ProductSchema.index({ name: 1, userId: 1 }, { unique: true });
const User = mongoose.model<IUser>('User', UserSchema);
const Product = mongoose.model<IProduct>('Product', ProductSchema);
const Cart = mongoose.model<ICart>('Cart', CartSchema);
const Order = mongoose.model<IOrder>('Order', OrderSchema);
export { User, Product, Cart, Order };