Home > front end >  Build fails with TypeError on functions using Nextjs with Mongoose
Build fails with TypeError on functions using Nextjs with Mongoose

Time:02-01

Next build fails with TypeError when calling model functions for methods and/or statics from pages/api.

The error is either property does not exist or expression is not callable.

I followed Mongoose Typescript recommendations.

import { Model, Schema, models, model } from 'mongoose';
import { User } from 'types/user';

interface UserModel extends Model<User> {
    findAuthenticated(hash: string): Promise<User>;
    getProfile(): Promise<User>;
}

const userSchema = new Schema<User, UserModel>({...});
...
export default models.User || model<User,UserModel>('User', userSchema);

Next.js 13 with Mongoose 6.8.2 and typescript 4.9.4.

CodePudding user response:

Using a generic helper function to type the model.

// models/user.ts
...
export default createModel<User,UserModel>('User', userSchema);

// utils/mongoose.ts
import { Model, Schema, models, model } from 'mongoose';

export function createModel<T, TModel = Model<T>>(
    modelName: string,
    schema: Schema<T>
): TModel {
    const mongooseModel = models[modelName] || model<T, TModel>(modelName, schema);
    return mongooseModel as TModel;
}
  • Related