node.js - 编译后无法覆盖“用户”模型。解决不了
问题描述
我收到此错误 OverwriteModelError: Cannot overwrite User
model 一旦编译。在后端/模型/userModel.js:34:23
代码:授权中间件:
import jwt from "jsonwebtoken";
import asyncHandler from "express-async-handler";
import User from "../models/userModel.js";
const protect = asyncHandler(async (req, res, next) => {
let token;
if (
req.headers.authorization &&
req.headers.authorization.startsWith("Bearer")
) {
try {
token = req.headers.authorization.split(" ")[1];
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = await User.findById(decoded.id).select("-password");
next();
} catch (error) {
console.error(error);
res.status(401);
throw new Error("Not authorized, token failed");
}
}
if (!token) {
res.status(401);
throw new Error("Not authorized, no token");
}
});
export { protect };
用户模型:
import mongoose from "mongoose";
import bcrypt from "bcryptjs";
const userSchema = mongoose.Schema(
{
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
isAdmin: {
type: Boolean,
required: true,
default: false,
},
},
{
timestamps: true,
}
);
userSchema.methods.matchPassword = async function (enteredPassword) {
return await bcrypt.compare(enteredPassword, this.password);
};
第 34:23 行:
const User = mongoose.model("User", userSchema);
export default User;
解决方案
问题是您在其他地方定义了模型。该线程包含对您的答案的最佳解释。
推荐阅读
- amazon-web-services - DLQ 中应该有什么样的异常?
- java - 所有值都添加到 HashMap 中,但只返回最后一个值
- python - adyen 加密的信用卡数据
- database - 更改订单或向 PlantUML ER 图表添加间距
- pandas - 汇合线图的自定义 X 轴
- javascript - 错误:解构变量时已在开关内声明了 Javascript 标识符
- mysql - 子选择导致奇怪的数据更改(为每个组获取前 N 行)
- windows - 如何使 Powershell 像 Linux/Unix 系统或“cmd”shell 一样自动完成?
- bixby - 如何用不同的语音在问答游戏中重复一个问题
- php - Laravel - 更改默认值 eloquent