【问题标题】:Next.JS and Mongoose modelsNext.JS 和 Mongoose 模型
【发布时间】:2021-08-04 01:51:53
【问题描述】:

我正在为一个客户构建一个非常简单的 next.js 应用程序,而在我的生活中,我无法弄清楚为什么我不断得到 Cannot overwrite User model 一旦编译。 每次我为任何路由的第一个请求关闭开发服务器时,它似乎都可以正常工作:addUser、authenticate、GET ......这一切都只适用于第一个请求。这是我连接到 MongoDB 的函数。

const connectDB = (handler) => async (req, res) => {
  if (mongoose.connections[0].readyState) {
    return handler(req, res);
  }
  await mongoose
    .connect(process.env.MONGO_URI, {
      useNewUrlParser: true,
      useCreateIndex: true,
      useFindAndModify: false,
      useUnifiedTopology: true,
    })
    .then(() => {
      return handler(req, res);
    });
};

const middleware = nc();
middleware.use(connectDB);
// middleware.use(authMiddleware);
module.exports = {
  connectDB,
  middleware,
};

和模型:

const mongoose = require("mongoose");
const bcrypt = require("bcryptjs");

const UserSchema = mongoose.Schema(
  {
    userName: {
      type: String,
      required: true,
    },
    password: {
      type: String,
      required: true,
    },
  },
  { timestamps: true }
);

UserSchema.pre("save", async function (next) {
  if (this.isModified("password")) {
    const salt = await bcrypt.genSalt(10);
    this.password = await bcrypt.hash(this.password, salt);
    next();
  } else {
    next(new Error("failed to encrypt password"));
  }
});

UserSchema.methods.comparePassword = async function (password, next) {
  const comparison = bcrypt.compare(password, this.password);
  if (!comparison) {
    return {
      isMatch: false,
      comparison: comparison,
    };
  } else {
    return {
      isMatch: true,
      comparison: comparison,
    };
  }
};

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

还有路线:

const handler = nc();
// handler.use(middleware);
handler.post(async (req, res) => {
  console.log(colors.bgBlue("Did run in route..."));
  try {
    const user = await User.findOne({ userName: req.body.email });
    const { isMatch } = await user.comparePassword(req.body.password);
    if (!isMatch) {
      return res.status(401).json({ error: "These passwords do not match." });
    }
    if (isMatch) {
      const payload = {
        user: {
          id: user.id,
        },
      };
      jwt.sign(
        payload,
        process.env.JWT_SECRET,
        {
          expiresIn: 3600,
        },
        (err, token) => {
          if (err) throw err;
          return res.json({ userID: user._id, token });
        }
      );
    }
  } catch (error) {
    console.log(error);
    res.status(500).json({ error: "There was an error adding that user." });
  }
});

export default connectDB(handler);

抱歉,拖了这么久,我真的不知道从哪里开始。我想念快递,但 SSR 非常好:(

【问题讨论】:

    标签: node.js mongodb next.js mongoose-schema


    【解决方案1】:

    当您调用comparePassword 时,您正在用user 覆盖User

    改成User.comparePassword

    说明:user 是您声明的变量,用于保存返回的文档,而 User 代表您从 mongoose 导入 \ 所需的模型。

    【讨论】:

      猜你喜欢
      • 2021-03-01
      • 2022-09-30
      • 2013-12-24
      • 2013-09-01
      • 2021-09-17
      • 2020-06-16
      • 2020-04-24
      • 2018-03-17
      相关资源
      最近更新 更多