猫鼬中的“唯一”字段存在问题
当我尝试使用现有的电子邮件或用户名创建新用户时,它会起作用。
现在它总是发送错误500。
但是仍然可以有效地处理错误消息吗?例如说(电子邮件已经存在或用户名已经存在)?
const mongoose = require('mongoose');
const uniqueValidator = require('mongoose-unique-validator');
const userSchema = mongoose.Schema({
email : {type: String, required: true, unique: true},
password: {type : String, required: true},
userid: {type : String},
username: {type : String, required: true, unique: true},
})
userSchema.plugin(uniqueValidator);
userSchema.index({ '$**': 'text' })
module.exports = mongoose.model('User', userSchema);
和节点控制器:
exports.createUser = (req, res, next) => {
bcrypt.hash(req.body.password, 10).then(
(hash) => {
const user = new User({
email: req.body.email,
password: hash,
userid:req.body.userid,
username:req.body.username,
});
user.save().then(
() => {
res.status(201).json({
message: 'User added successfully!'
});
}
).catch(
(error) => {
res.status(500).json({
error: error
});
}
);
}
);
};
感谢帮助
答案 0 :(得分:1)
每个人都认为它已经完成,就在前面处理您发送的错误女巫,该女巫作为捕获状态为500的女巫,它会像这样: {驱动程序:true,名称:“ MongoError”,索引:0,代码:11000,keyPattern:{…},…} 码:11000 司机:真实 索引:0 keyPattern: 电子邮件:1 proto :对象 核心价值: 电子邮件:“ gjhk@ex.com” proto :对象 名称:“ MongoError” proto :对象}
react中的示例句柄:
register = async (name, lastName, email, password, cb) => {
try {
const res = await fetch('http://', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name, lastName, email, password })
})
const result = await res.json()
if (result.code === 11000) {
cb(11000)
}
if (res.status === 201) {
localStorage.setItem('authenticated', true)
localStorage.setItem('userName', result.user.name)
localStorage.setItem('userLastName', result.user.lastName)
localStorage.setItem('token', result.token)
cb()
} else {
cb(400)
}
} catch{
cb('Błąd serwera')
}
}
对于回复的质量感到抱歉,这是我首先用英语发表的评论。
答案 1 :(得分:0)
您可以检查代码开头是否使用了电子邮件或用户名,并使用如下自定义消息发送400-BadRequest:
exports.createUser = async (req, res, next) => {
let user = await User.findOne({ email: req.body.email });
if (user) return res.status(400).send("Email already exists");
user = await User.findOne({ username: req.body.username});
if (user) return res.status(400).send("Username already exists.");
...
请注意,我放置了异步,以便能够使用await。
我也建议您使用async / await而不是catch块来摆脱回调地狱。您可以使用async / await这样编写代码:
exports.createUser = async (req, res, next) => {
try {
const { email, password, userId, username } = req.body;
let user = await User.findOne({ email });
if (user) return res.status(400).json({ error: "Email already exists" });
user = await User.findOne({ username });
if (user) return res.status(400).send({ error: "Username already exists" });
user = new User({ email, password, userId, username });
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(user.password, salt);
await user.save();
res.status(201).json({ message: "User added successfully!" });
} catch (error) {
res.status(500).json({ error });
}
};