0

I was gonna use statics in mongoose with typescript but typescript does not understand this static.

I found the type definition from website and it said like this

import { Document, model, Model, Schema } from "mongoose";

var UserSchema = new Schema({});
UserSchema.statics.static1 = function () {
  return "";
};

interface IUserDocument extends Document {}
interface IUserModel extends Model<IUserDocument> {
  static1: () => string;
}

var UserModel: IUserModel = model<IUserDocument, IUserModel>(
  "User",
  UserSchema
);
UserModel.static1(); // static methods are available

yes it worked before I set something in the Document{}

import { Document, model, Model, Schema } from "mongoose";

var UserSchema = new Schema({
  name: {
    type: String,
    maxlength: 50,
  },
});
UserSchema.statics.static1 = function () {
  return "";
};

interface IUserDocument extends Document {
  name: string;
}
interface IUserModel extends Model<IUserDocument> {
  static1: () => string;
}

var UserModel: IUserModel = model<IUserDocument, IUserModel>(
  "User",
  UserSchema
);
UserModel.static1(); // Property 'static1' is missing in type 'Model<IUserDocument>' but required in type 'IUserModel'

I don't know why this weird problem occurred... please help me

1 Answer 1

1

Ok I solved the problem of it by myself. If there is anyone who experience my case, check this.

If you go to the model's definition, you can see that

export function model<T extends Document, U extends Model<T>>(
    name: string,
    schema?: Schema<T, U>,
    collection?: string,
    skipInit?: boolean
  ): U;

The thing you should focus on is that "schema:Schema<T,U>"

it means that the second argument of model() should takes that two definition

so, before you set the schema, you should define that

"const userSchema : mongoose.Schema<T extends Document,U extends Model> = newSchema({})"

And finally, I can avoid this horrible error.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.