0

目前,当向 findOneAndUpdate 提供 id 时,它不会返回自动生成的 id。

所以我创建了扩展方法来克服这个问题。但是打字稿抱怨打字。需要帮助。

我创建了如下扩展方法。

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<QueryWithHelpers<T | null, T>>; // Here I am getting error as "Type 'T' does not satisfy the constraint 'Document<any, {}>'"
  }
}



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<QueryWithHelpers<T | null, T>> {
  const model = this as mongoose.Model<T>;
  if (filter.id) {
    return model.findOneAndUpdate(filter, update);
  } else {
    return model.findById((await model.create((update as any).$set)).id);
  }
};

我想像下面这样使用它。

datasource = await DatasourceModel(
      await this.projectContext,
    ).findOneAndUpsert(
      { id: datasource.id },
      {
        $set: {
          name: datasource.name,
          type: datasource.type,
          source: datasource.source,
        },
      },
    );

我的数据源模型如下所示。

export class Datasource extends ModelBase {
  @prop()
  authTokenId?: number;
}

export const DatasourceModel = (connection: Connection) => {
  return getModelForClass(Datasource, connection);
};

在声明期间我收到错误,因为“类型'T'不满足约束'Document<any,{}>'”?

如果我写"T extends mongoose.Document<any, {}>"在模型声明中,那么不会给出错误,但是在调用该方法期间它会给出错误"Property 'name' is missing in type 'Document<any, {}>' but required in type 'Datasource'"

谁能帮助我在这里需要做的事情?

4

1 回答 1

0

好的,以下签名对我有用。我在签名和实际实现中都添加了扩展。但是在模型签名中不需要扩展,因为默认情况下它只进行扩展。

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>;
  }
}
于 2021-06-09T08:30:07.477 回答