Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Problems with Schema.query's type definition #10545

Closed
GCastilho opened this issue Aug 6, 2021 · 2 comments
Closed

Problems with Schema.query's type definition #10545

GCastilho opened this issue Aug 6, 2021 · 2 comments
Labels
typescript Types or Types-test related issue / Pull Request
Milestone

Comments

@GCastilho
Copy link
Contributor

bug

What is the current behavior?

The type definition for the Schema.query doesn't seems to be working

What is the expected behavior?

If I define a custom query for a schema, the this type is resolved to any. If I try to provide a custom this type I get a "Type 'T' is not assignable to type...":

// Type 'T' is not assignable to type 'Query<any, any, {}, any>'.ts(2322)
SomeSchema.query.someQuery = function(
    this: QueryWithHelpers<ResultType, DocType>
): QueryWithHelpers<ResultType, DocType> {
	return ...
}

This previously worked (when using @types/mongoose) defining this to DocumentQuery<ResultType, DocType> although they didn't have a type for the query property

What are the versions of Node.js, Mongoose and MongoDB you are using? Note that "latest" is not a version.

5.13.5

@IslandRhythms IslandRhythms added the typescript Types or Types-test related issue / Pull Request label Aug 6, 2021
@vkarpov15 vkarpov15 modified the milestones: 5.13.6, 5.13.7, 5.13.8 Aug 8, 2021
@vkarpov15
Copy link
Collaborator

You're right that this is any by default in query helpers, we're working on that.

But, in the meantime, the below script seems to compile fine. Can you please provide your tsconfig and check whether the below script compiles on your setup?

import { Schema, model, Document, Types, Query, Model, QueryWithHelpers } from 'mongoose';

interface QueryHelpers {
  byName(name: string): QueryWithHelpers<Array<ITest>, ITest, QueryHelpers>;
}

const schema: Schema<ITest, Model<ITest, QueryHelpers>> = new Schema({
  name: { type: 'String' },
  tags: [String],
  docs: [{ nested: { id: Number, tags: [String] } }],
  endDate: Date
});

schema.query.byName = function(this: QueryWithHelpers<any, ITest>, name: string): QueryWithHelpers<any, ITest> {
  return this.find({ name });
};

@GCastilho
Copy link
Contributor Author

I know it's closed but I do confirm this worked as a workaround

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
typescript Types or Types-test related issue / Pull Request
Projects
None yet
Development

No branches or pull requests

3 participants