I am trying to create generic extension method on all mongoose model. But I am unable to avail method on model when use runtime.
I have implemented as following.
mongoose.model.prototype.findOneAndUpsert = async function <
T extends mongoose.Document<any, {}>
>(
filter?: FilterQuery<T>,
update?: UpdateQuery<T>,
options?: QueryOptions | null,
callback?: (err: any, doc: T | null, res: any) => void,
): Promise<T> {
const model = this as mongoose.Model<T>;
if (filter.id) {
return model.findOneAndUpdate(filter, update, options, callback);
} else {
return model.findById((await model.create((update as any).$set)).id);
}
};
Is this possible or not supported at all? Or I am doing in a wrong way?
I am trying to use it as following. DatasourceModel is a Typegoose model.
DatasourceModel.findOneAndUpsert(someParams)
Error I am getting is as below.
TypeError: datasource_1.DatasourceModel(...).findOneAndUpsert is not a function
I have declared mongoose module as following which helps during compile time. But not during runtime.
declare module 'mongoose' { interface Model<T> extends NodeJS.EventEmitter, AcceptsDiscriminator { findOneAndUpsert<T>( filter?: FilterQuery<T>, update?: UpdateQuery<T>, options?: QueryOptions | null, callback?: (err: any, doc: T | null, res: any) => void, ): Promise<T>; } }