Home > database >  Mongoose 6 typescript doesn't allow $inc
Mongoose 6 typescript doesn't allow $inc

Time:09-22

When migrating from mongoose 5.x to 6.x there was an error with the typescript, specifically with the UpdateQuery $inc as the type is set to undefined. I am using the built-in types not the @types/mongoose Here is an example:

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

The error I receive is this:

   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>'

Is this a type error with mongoose 6 or has the update or the atomic increment changed?

CodePudding user response:

The issue is the casing of your PrintSettings interface. The types are expecting PrintSettings.currentBatch to be one of:

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

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

You are using Number instead of number, notice the lowercase "n". The following works:

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

Basically, for the interface use everyday types. Which is slightly different than the types passed to the Schema.

  • Related