【问题标题】:Mongoose 6 typescript doesn't allow $incMongoose 6 打字稿不允许 $inc
【发布时间】:2021-11-15 07:58:54
【问题描述】:

从 mongoose 5.x 迁移到 6.x 时,打字稿出现错误,特别是 UpdateQuery $inc,因为类型设置为未定义。我使用的是内置类型而不是 @types/mongoose 这是一个示例:

  export interface PrintSettings extends Document {
    _id: String
    currentBatch: Number
  }
  
  const PrintSettingsSchema: Schema<PrintSettings> = new Schema(
    {
      _id: { type: String },
      currentBatch: { type: Number, default: 0, min: 0 },
    },
    { timestamps: true }
    )
    
    let inc = await PrintSettingsModel.findOneAndUpdate(
      { _id: settingsId },
      { $inc: { currentBatch: 1 } }, // <------ Here is where the error occurs
      { useFindAndModify: false, new: true }
    )

我收到的错误是这样的:

   No overload matches this call.
  Overload 1 of 3, '(filter: FilterQuery<PrintSettings>, update: UpdateQuery<PrintSettings>, options: QueryOptions & { rawResult: true; }, callback?: ((err: CallbackError, doc: any, res: any) => void) | undefined): Query<...>', gave the following error.
    Type '{ currentBatch: number; }' is not assignable to type 'undefined'.
  Overload 2 of 3, '(filter: FilterQuery<PrintSettings>, update: UpdateQuery<PrintSettings>, options: QueryOptions & { upsert: true; } & ReturnsNewDoc, callback?: ((err: CallbackError, doc: PrintSettings, res: any) => void) | undefined): Query<...>', gave the following error.
    Type '{ currentBatch: number; }' is not assignable to type 'undefined'.
  Overload 3 of 3, '(filter?: FilterQuery<PrintSettings> | undefined, update?: UpdateQuery<PrintSettings> | undefined, options?: QueryOptions | null | undefined, callback?: ((err: CallbackError, doc: PrintSettings | null, res: any) => void) | undefined): Query<...>', gave the following error.
    Type '{ currentBatch: number; }' is not assignable to type 'undefined'.ts(2769)
  index.d.ts(2576, 5): The expected type comes from property '$inc' which is declared here on type 'UpdateQuery<PrintSettings>'

这是 mongoose 6 的类型错误还是更新或原子增量已更改?

【问题讨论】:

  • 您是使用内置的index.d.ts 还是使用@types/mongoose?官方index.d.ts 确实包括$inc。你能检查 node_modules mongoose 中的那个文件,看看那一行是否存在?
  • 我只是使用内置类型而不是 @types/mongoose
  • 如果你进入 node_modules mongoose,你会在 index.d.ts 中看到那一行吗?
  • 是的,我看到那行,文件完全一样

标签: typescript mongodb mongoose node-modules


【解决方案1】:

问题在于PrintSettings 接口的外壳。这些类型期望 PrintSettings.currentBatch 是以下类型之一:

type _UpdateQuery<TSchema> = {
  // ...
  $inc?: OnlyFieldsOfType<TSchema, NumericTypes | undefined> & AnyObject;
  // ...
}

type NumericTypes = number | Decimal128 | mongodb.Double | mongodb.Int32 | mongodb.Long;

您使用的是Number 而不是number,请注意小写的“n”。以下作品:

export interface PrintSettings extends Document {
  _id: string;
  currentBatch: number;
}

基本上,对于接口使用everyday types。这与传递给 Schema 的类型略有不同。

【讨论】:

  • 在 v5.x 中,如果我使用数字而不是数字,输入会给我一个错误,但我很高兴现在已修复!谢谢。
猜你喜欢
  • 2019-07-28
  • 1970-01-01
  • 1970-01-01
  • 2020-07-26
  • 1970-01-01
  • 1970-01-01
  • 2016-03-21
  • 2020-08-01
  • 2021-05-27
相关资源
最近更新 更多