Mongoose plugins in next.js

39 views Asked by At

How to properly register plugins with mongoose and next.js. Plugin in question is mongoose-paginate-v2, but I imagine that this is related to most of plugin as they rely on middleware and need to be applied before compiling models.

The issue with next.js and mongoose models starts here:

UserSchema.plugin(paginate); 
export const User = mongoose.model<User, mongoose.PaginateModel<User>>("users", UserSchema);

This throws error: OverwriteModelError: Cannot overwrite users model once compiled. That I solved by adding module check:

export const User = mongoose.models.users || 
    mongoose.model<User, mongoose.PaginateModel<User>>("users", UserSchema);

And this now creates issue with paginate plugin in typescript and when I try to use it: \_models_UserWEBPACK_IMPORTED_MODULE_1.User.paginate is not a function

0

There are 0 answers