Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { Document, Types, Model, Schema, model, DocumentQuery } from 'mongoose';
- interface IListDocument extends Document {
- name: string;
- userId: Types.ObjectId;
- sharedOwnerIds: Array<Types.ObjectId>;
- date: Date;
- notes: string;
- items: Array<{
- name: string;
- hasBeenbought: boolean;
- category: Types.ObjectId;
- order: number;
- }>;
- }
- interface IListQueryHelpers {
- byUserWithAccess: (
- userId: Types.ObjectId
- ) => DocumentQuery<IListDocument, IListDocument, IListQueryHelpers>;
- }
- interface IListModel extends Model<IListDocument, IListQueryHelpers> {
- findByUserWithAccess: (userId: Types.ObjectId) => Promise<IListDocument[]>;
- }
- // item subdoc
- const itemSchema = new Schema({
- name: String,
- hasBeenBought: { type: Boolean, default: false },
- category: Schema.Types.ObjectId,
- order: Number
- });
- // schema
- const listSchema = new Schema({
- name: String,
- userId: Schema.Types.ObjectId,
- sharedOwnerIds: [Schema.Types.ObjectId],
- date: Date,
- notes: { type: String, default: '' },
- items: [itemSchema]
- });
- // query helpers
- listSchema.query.byUserWithAccess = function(userId: Types.ObjectId) {
- return this.or([
- { userId },
- { sharedOwnerIds: { $elemMatch: { $eq: userId } } }
- ]);
- };
- // static helpers
- listSchema.statics.findByUserWithAccess = function(userId: Types.ObjectId) {
- return this.find()
- .byUserWithAccess(userId)
- .exec();
- };
- // model
- export const List = model<IListDocument, IListModel>(
- 'List',
- listSchema,
- 'lists'
- );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement