0

我正在尝试在所有猫鼬模型上创建通用扩展方法。但是在使用运行时时我无法在模型上使用方法。

我已经实现如下。

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);
  }
};

这是可能的还是根本不支持?还是我做错了?

我正在尝试按以下方式使用它。DatasourceModel 是一个 Typegoose 模型。

DatasourceModel.findOneAndUpsert(someParams)

我得到的错误如下。

TypeError: datasource_1.DatasourceModel(...).findOneAndUpsert is not a function

我已将 mongoose 模块声明如下,这在编译时会有所帮助。但不是在运行时。

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>; } }

4

0 回答 0