Skip to content

Instantly share code, notes, and snippets.

@iamdanthedev
Last active June 17, 2023 04:56
Show Gist options
  • Save iamdanthedev/a63fc9ae83819f4587bb498ac10a689f to your computer and use it in GitHub Desktop.
Save iamdanthedev/a63fc9ae83819f4587bb498ac10a689f to your computer and use it in GitHub Desktop.
Typescript fully typed mongoose workflow incl. virtuals, statics and hooks
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