Automattic / mongoose

MongoDB object modeling designed to work in an asynchronous environment.
https://mongoosejs.com
MIT License
26.9k stars 3.83k forks source link

castForQuery() for custom SchemaTypes missing in TypeScript #14347

Closed samantha-statsig closed 7 months ago

samantha-statsig commented 8 months ago

Prerequisites

Mongoose version

7.0.0

Node.js version

16.15.0

MongoDB server version

5.1.0

Typescript version (if applicable)

4.8.4

Description

SchemaType.castForQuery() is missing from the SchemaType TypeScript declarations.

This prevents me from adding support for other Mongo query operators on my custom SchemaType such as $regex and $mod as recommended by the Mongoose docs: https://mongoosejs.com/docs/migrating_to_7.html#removed-castforquerywrapper

This is what the TypeScript declarations look like: schematypes.d.ts

Steps to Reproduce

Mongoose, Node.js, MongoDB, and TypeScript versions are attached to this issue and should be enough to reproduce.

Expected Behavior

No response

samantha-statsig commented 8 months ago

@IslandRhythms Is there anything else that I can help provide? I am happy to provide more info to help you repro.

vkarpov15 commented 7 months ago

@samantha-statsig the following script compiles fine with Mongoose 7.6.8 and TypeScript 5.3.3 with --strict. Can you please modify the following script to demonstrate the issue you're seeing?

import mongoose from 'mongoose';

class Int8 extends mongoose.SchemaType {
  constructor(key: string, options: Record<string, any>) {
    super(key, options, 'Int8');
  }

  // `cast()` takes a parameter that can be anything. You need to
  // validate the provided `val` and throw a `CastError` if you
  // can't convert it.
  cast(val: any) {
    let _val = Number(val);
    if (isNaN(_val)) {
      throw new Error('Int8: ' + val + ' is not a number');
    }
    _val = Math.round(_val);
    if (_val < -0x80 || _val > 0x7F) {
      throw new Error('Int8: ' + val +
        ' is outside of the range of valid 8-bit ints');
    }
    return _val;
  }

  castForQuery($conditional: string, val: any) {
    return val;
  }
}

// Don't forget to add `Int8` to the type registry
// @ts-ignore
mongoose.Schema.Types.Int8 = Int8;

const testSchema = new mongoose.Schema({ test: Int8 });
const Test = mongoose.model('CustomTypeExample', testSchema);
github-actions[bot] commented 7 months ago

This issue is stale because it has been open 14 days with no activity. Remove stale label or comment or this will be closed in 5 days

github-actions[bot] commented 7 months ago

This issue was closed because it has been inactive for 19 days and has been marked as stale.