【发布时间】:2020-03-03 20:52:07
【问题描述】:
Mongoose 中的 Unique 字段有问题
当我尝试使用现有电子邮件或用户名创建新用户时,它可以工作。
现在它总是发送错误 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
});
}
);
}
);
};
感谢您的帮助
【问题讨论】:
标签: mongoose mean-stack