Advertisement
Guest User

Untitled

a guest
Jul 9th, 2019
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { Document, Types, Model, Schema, model, DocumentQuery } from 'mongoose';
  2.  
  3. interface IListDocument extends Document {
  4.   name: string;
  5.   userId: Types.ObjectId;
  6.   sharedOwnerIds: Array<Types.ObjectId>;
  7.   date: Date;
  8.   notes: string;
  9.   items: Array<{
  10.     name: string;
  11.     hasBeenbought: boolean;
  12.     category: Types.ObjectId;
  13.     order: number;
  14.   }>;
  15. }
  16.  
  17. interface IListQueryHelpers {
  18.   byUserWithAccess: (
  19.     userId: Types.ObjectId
  20.   ) => DocumentQuery<IListDocument, IListDocument, IListQueryHelpers>;
  21. }
  22.  
  23. interface IListModel extends Model<IListDocument, IListQueryHelpers> {
  24.   findByUserWithAccess: (userId: Types.ObjectId) => Promise<IListDocument[]>;
  25. }
  26.  
  27. // item subdoc
  28. const itemSchema = new Schema({
  29.   name: String,
  30.   hasBeenBought: { type: Boolean, default: false },
  31.   category: Schema.Types.ObjectId,
  32.   order: Number
  33. });
  34.  
  35. // schema
  36. const listSchema = new Schema({
  37.   name: String,
  38.   userId: Schema.Types.ObjectId,
  39.   sharedOwnerIds: [Schema.Types.ObjectId],
  40.   date: Date,
  41.   notes: { type: String, default: '' },
  42.   items: [itemSchema]
  43. });
  44.  
  45. // query helpers
  46. listSchema.query.byUserWithAccess = function(userId: Types.ObjectId) {
  47.   return this.or([
  48.     { userId },
  49.     { sharedOwnerIds: { $elemMatch: { $eq: userId } } }
  50.   ]);
  51. };
  52.  
  53. // static helpers
  54. listSchema.statics.findByUserWithAccess = function(userId: Types.ObjectId) {
  55.   return this.find()
  56.     .byUserWithAccess(userId)
  57.     .exec();
  58. };
  59.  
  60. // model
  61. export const List = model<IListDocument, IListModel>(
  62.   'List',
  63.   listSchema,
  64.   'lists'
  65. );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement