Mongoose/NextJS - Model is not defined / Cannot overwrite model once compiled Mongoose/NextJS - Model is not defined / Cannot overwrite model once compiled express express

Mongoose/NextJS - Model is not defined / Cannot overwrite model once compiled


I've managed to fix it. There were two problems here.

1) "UserModel" variable doesn't exist in the pre middleware. Solved by instantiating this.constructor which apparently solves the issue (will need further testing)

2) There's apparently a issue with NextJS building everything, it seems like it's trying to create a new model whenever I use any function from UserModel. This is fixed exporting the already created model

const mongoose = require("mongoose");const errorHandler = require("../helpers/errorHandler");const Schema = mongoose.Schema;const UserSchema = new Schema({  userName: String,  userPassword: String,  userBanned: Boolean,  userType: String,  registeredDate: { type: Date, default: Date.now },  registeredIP: String,  lastLoginDate: { type: Date, default: Date.now },  lastLoginIP: String,});UserSchema.pre("save", async function () {  try {    const User = this.constructor;    const userExists = await User.find({      userName: this.get("userName"),    })      .lean()      .exec();    if (userExists.length > 0) {      throw new Error(errorHandler.errors.REGISTER_USERNAME_EXISTS);    }  } catch (err) {    throw new Error(errorHandler.errors.REGISTER_USERNAME_EXISTS);  }});module.exports = mongoose.models.User || mongoose.model("User", UserSchema);