猫鼬 6 打字稿不允许 $inc

Mongoose 6 typescript doesn't allow $inc

从 mongoose 5.x 迁移到 6.x 时,typescript 出现错误,特别是 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 的类型错误还是更新或原子增量发生了变化?

问题出在您的 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.

的类型略有不同