Last active
June 17, 2023 04:56
-
-
Save iamdanthedev/a63fc9ae83819f4587bb498ac10a689f to your computer and use it in GitHub Desktop.
Typescript fully typed mongoose workflow incl. virtuals, statics and hooks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Document, model, Model, Schema } from 'mongoose'; | |
import { withFindOrCreate, WithFindOrCreate } from '../utils/findOrCreate'; | |
import { NutrientUnitInstance, NutrientUnitModel } from '../NutrientUnit/NutrientUnit'; | |
import { ObjectID } from 'bson'; | |
/** | |
* Nutrient (e.g. calcium) | |
*/ | |
export interface Nutrient { | |
code: string; | |
title: string; | |
displayUnitCode: string; | |
/** | |
* @deprecated | |
*/ | |
displayUnitId: ObjectID; | |
} | |
export type NutrientInstance = Nutrient & Document & { | |
displayUnit: Promise<NutrientUnitInstance>; | |
}; | |
export type NutrientInstanceStatic = Model<NutrientInstance> & | |
WithFindOrCreate<NutrientInstance>; | |
// findOrCreate adds a typed static method on the Model | |
// https://gist.github.com/rasdaniil/6d411a4f6441b5548eeadadfd1f7b60a | |
export const nutrientSchema = withFindOrCreate( | |
new Schema({ | |
code: { | |
type: String, | |
index: true, | |
required: true, | |
lowercase: true, | |
}, | |
title: { | |
type: String, | |
required: true, | |
}, | |
displayUnitCode: { | |
type: String, | |
required: true, | |
}, | |
displayUnitId: { | |
type: String, | |
} | |
}), | |
); | |
// @ts-ignore | |
nutrientSchema.post('init', async function(this: NutrientInstance) { | |
// noinspection JSDeprecatedSymbols | |
if (!this.displayUnitCode && this.displayUnitId) { | |
const unit = await NutrientUnitModel.findById(this.displayUnitId); | |
if (unit) { | |
this.displayUnitCode = unit.code; | |
await this.save(); | |
} | |
} | |
}); | |
nutrientSchema.virtual('displayUnit').get(async function(this: NutrientInstance) { | |
if (!this.displayUnitCode) { | |
return Promise.resolve(null); | |
} | |
return await NutrientUnitModel.findOne({ code: this.displayUnitCode }); | |
}); | |
export const NutrientModel = model<NutrientInstance>( | |
'Nutrient', | |
nutrientSchema, | |
'nutrient', | |
) as NutrientInstanceStatic; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment