【发布时间】: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