且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Mongoose/NextJS - 模型未定义/编译后无法覆盖模型

更新时间:1970-01-01 07:59:30

我已经设法解决了.这里有两个问题.

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

1) UserModel"变量在预中间件中不存在.通过实例化 this.constructor 解决,这显然解决了问题(需要进一步测试)

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) NextJS 构建所有东西显然存在问题,每当我使用 UserModel 中的任何函数时,它似乎都在尝试创建一个新模型.这是固定导出已创建的模型

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);