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

a11xaf1n  于 2023-08-04  发布在  Go
关注(0)|答案(3)|浏览(117)

TL;DR EDIT:如果你来自Google,这是解决方案:

module.exports = mongoose.models.User || mongoose.model("User", UserSchema);

字符串
对于非TL; DR回答,检查接受的回答。

我在一个NextJS网站上工作,在后端我使用Mongoose和Express。每当我使用signUp函数时,我在后端得到这个错误:

```
{"name":"Test","hostname":"DESKTOP-K75DG72","pid":7072,"level":40,"route":"/api/v1/signup","method":"POST","errorMessage":"UserModel is not defined","msg":"","time":"2020-06-17T23:51:34.566Z","v":0}
```
型
我怀疑这个错误是因为我在其他控制器中使用了UserModel。这个错误是没有发生,直到我做了一个新的控制器。所以我的问题是,如何解决这个问题/如何在不同的控制器/中间件中使用相同的模型?
我认为这个问题与[node.js - Cannot overwrite model once compiled Mongoose](https://stackoverflow.com/questions/19051041/cannot-overwrite-model-once-compiled-mongoose)这篇文章有关,我早些时候得到了这个错误,但不知何故设法修复了它。

**EDIT:错误在models/User.js,在预保存中间件中,UserModel没有在级别上定义,如何验证该用户名是否已经存在,如果存在则拒绝新文档?**

在**controllers/RegisterLogin.js [bug发生的地方]**

```
const UserModel = require("../models/User");
// More packages...

async function signUp(req, res) {
  try {
    const value = await signUpSchema.validateAsync(req.body);
    const response = await axios({
      method: "POST",
      url: "https://hcaptcha.com/siteverify",
      data: qs.stringify({
        response: value.token,
        secret: process.env.HCAPTCHA,
      }),
      headers: {
        "content-type": "application/x-www-form-urlencoded;charset=utf-8",
      },
    });

    if (!response.data.success) {
      throw new Error(errorHandler.errors.HCAPTCHA_EXPIRED);
    }

    const hashPassword = await new Promise((res, rej) => {
      bcrypt.hash(
        value.password,
        parseInt(process.env.SALTNUMBER, 10),
        function (err, hash) {
          if (err) rej(err);
          res(hash);
        }
      );
    });

    await UserModel.create({
      userName: value.username,
      userPassword: hashPassword,
      userBanned: false,
      userType: "regular",
      registeredIP: req.ip || "N/A",
      lastLoginIP: req.ip || "N/A",
    });

    return res.status(200).json({
      success: true,
      details:
        "Your user has been created successfully! Redirecting in 6 seconds",
    });
  } catch (err) {
    const { message } = err;
    if (errorHandler.isUnknownError(message)) {
      logger.warn({
        route: "/api/v1/signup",
        method: "POST",
        errorMessage: message,
      });
    }

    return res.status(200).json({
      success: false,
      details: errorHandler.parseError(message),
    });
  }
}

module.exports = { signUp };
```
型
在**controllers/Profile.js [如果我在这里使用UserModel,它会破坏一切]**

```
const UserModel = require("../models/User");
//plus other packages...

async function changePassword(req, res) {
  try {
    const value = await passwordChangeSchema.validateAsync(req.body);

    const username = await new Promise((res, rej) => {
      jwt.verify(value.token, process.env.PRIVATE_JWT, function (err, decoded) {
        if (err) rej(err);
        res(decoded.username);
      });
    });

    const userLookup = await UserModel.find({ userName: username });

    if (userLookup == null || userLookup.length == 0) {
      throw new Error(errorHandler.errors.BAD_TOKEN_PROFILE);
    }

    const userLookupHash = userLookup[0].userPassword;

    try {
      // We wrap this inside a try/catch because the rej() doesnt reach block-level
      await new Promise((res, rej) => {
        bcrypt.compare(value.currentPassword, userLookupHash, function (
          err,
          result
        ) {
          if (err) {
            rej(errorHandler.errors.BAD_CURRENT_PASSWORD);
          }
          if (result == true) {
            res();
          } else {
            rej(errorHandler.errors.BAD_CURRENT_PASSWORD);
          }
        });
      });
    } catch (err) {
      throw new Error(err);
    }

    const hashPassword = await new Promise((res, rej) => {
      bcrypt.hash(
        value.newPassword,
        parseInt(process.env.SALTNUMBER, 10),
        function (err, hash) {
          if (err) rej(err);
          res(hash);
        }
      );
    });

    await UserModel.findOneAndUpdate(
      { userName: username },
      { userPassword: hashPassword }
    );
    return res.status(200).json({
      success: true,
      details: "Your password has been updated successfully",
    });
  } catch (err) {
    const { message } = err;
    if (errorHandler.isUnknownError(message)) {
      logger.warn({
        route: "/api/v1/changepassword",
        method: "POST",
        errorMessage: message,
      });
    }

    return res.status(200).json({
      success: false,
      details: errorHandler.parseError(message),
    });
  }
}
```
型
At**models/User.js**

```
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 () {
  const userExists = await UserModel.find({
    userName: this.get("userName"),
  })
    .lean()
    .exec();
  if (userExists.length > 0) {
    throw new Error(errorHandler.errors.REGISTER_USERNAME_EXISTS);
  }
});

module.exports = mongoose.model("User", UserSchema);
```
型
agyaoht7

agyaoht71#

我已经修好了。这里有两个问题。
1)“UserModel”变量在预中间件中不存在。通过示例化这个.constructor解决了这个问题(需要进一步测试)
2)显然,NextJS构建所有内容时存在一个问题,每当我使用UserModel中的任何函数时,它似乎都试图创建一个新模型。导出已创建的模型已修复此问题

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

字符串

p1iqtdky

p1iqtdky2#

对我来说,这只是简单地添加了斯坦·卢纳的最后一行回答:

module.exports = mongoose.models.User || mongoose.model("User", UserSchema);

字符串

c3frrgcw

c3frrgcw3#

最简单的答案(2023)

发生的事情是Next.js喜欢不断重建您的代码,导致Mongoose(mongoose.models)中该高速缓存出现一些问题。
基本上,你要做的不是每次重建时都创建一个新模型,而是检查模型是否已经加载到Mongoose缓存中,如果是,就使用它而不是重新创建它。
所以在你的代码中你要替换

mongoose.model('Profile', profileSchema);

字符串

mongoose.models.Profile ?? mongoose.model('Profile', profileSchema);


在更简单的代码中,它所做的基本上是这样的:

let Profile;
if(mongoose.models.Profile) Profile = mongoose.models.Profile
else Profile = mongoose.model('Profile', profileSchema);

相关问题