Skip to content

Instantly share code, notes, and snippets.

@iamdanthedev
Created December 27, 2017 05:39
Show Gist options
  • Save iamdanthedev/6d411a4f6441b5548eeadadfd1f7b60a to your computer and use it in GitHub Desktop.
Save iamdanthedev/6d411a4f6441b5548eeadadfd1f7b60a to your computer and use it in GitHub Desktop.
findOrCreate mongoose typescript plugin
import { Document, Model, Schema } from 'mongoose';
import { ObjectID } from 'bson';
/**
* Find or create mongoose static function creator
*/
export type WithFindOrCreate<T extends Document> = {
findOrCreate: (id?: string | ObjectID | null) => T;
};
export function findOrCreateFactory<T extends Model<any>>() {
return async function(this: T, id?: string | ObjectID | null) {
if (!id || !ObjectID.isValid(id)) {
return new this();
}
const $id = new ObjectID(id);
const item = await this.findById($id);
return item ? item : new this();
};
}
export function withFindOrCreate<T extends Model<any>>(schema: Schema) {
schema.statics.findOrCreate = findOrCreateFactory<T>();
return schema;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment