'Getting error: The expression is not callable Mongoose NextJS

I trying to save data to a mongoose model on NextJS page. I get a typescript error on this line:

await User.create(data)

This expression is not callable. Each member of the union type '{ <Z = Document | _AllowStringsForIds<Pick<Pick<_LeanDocument<Document>, "_id" | "__v" | "id">, "_id" | "__v" | "id">>>(doc: Z): Promise<...>; <Z = Document<...> | _AllowStringsForIds<...>>(docs: Z[], options?: SaveOptions): Promise<...>; <Z = Document<...> | _AllowStringsForIds<...>>(...docs: Z[]): Promis...' has signatures, but none of those signatures are compatible with each other.

The code works - I can see the data added into the database, but

  1. Deploy on heroku fails with the same error
  2. I want to clear this error on my VSCode [Problems] tab as well (anoying)

Here is what I export from my User model:

export default  (mongoose.models.User || mongoose.model('User', UserSchema));


Solution 1:[1]

Even though a little older, leaving my insights here:

I had the same issue and found I could make it work without @ts-ignore by explicitly giving the mongoose.models.User the same type as used with the schema.

export interface User {
  username: string;
  password: string;
}

const schema = new mongoose.Schema<User>(
  {
    username: {
      type: String,
      required: true,
    },
    password: {
      type: String,
      required: true,
    },
  }
);
    
export default (mongoose.models.User as mongoose.Model<User>) || mongoose.model('User', schema);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 robbash