【问题标题】:Mongoose (Typegoose) extension method type errorMongoose (Typegoose) 扩展方法类型错误
【发布时间】:2021-08-26 03:28:07
【问题描述】:

目前当 id 提供给 findOneAndUpdate 时,它​​不会返回自动生成的 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'”?

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

任何人都可以帮忙解决我在这里需要做的事情吗?

【问题讨论】:

  • 您使用的版本是什么(typescript、mongoose、typegoose),您是否已经尝试将选项new: true 添加到findOneAndUpdate
  • tpyegoose 5.9.1,打字稿 4.2.4,猫鼬 5.12.7
  • 试过新的:真。但它也没有返回新生成的 ID。它返回空 ID。
  • 似乎以下是相关的...stackoverflow.com/questions/17244363/…

标签: node.js typescript mongodb mongoose typegoose


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2020-07-02
    • 1970-01-01
    • 2022-09-23
    • 2020-04-15
    • 1970-01-01
    • 2021-12-01
    • 2022-12-17
    • 1970-01-01
    • 2014-12-21
    相关资源
    最近更新 更多