我正在进行注册后的请求,但我想弹出错误,如果用户名已经采取。 有什么建议吗?
以下是我的邮路:
app.post('/addUser', (req,res) => {
const addUser = new User({username: req.body.username, password: req.body.password})
addUser.save().then(result => res.status(200).json(result)).catch((err) => console.log(err))
})
替代方法,具体取决于所需的错误样式。
const users = new mongoose.Schema(
{
username: {type: String, unique: 'That username is already taken'}
},
{ timestamps: true }
)
现在,mongo将对用户名进行索引,并在插入之前对其进行检查。 如果它不是唯一的,将抛出一个错误。
您可以使用mongoose
的findone
方法
app.post('/addUser', async (req,res) => {
//validation
var { username, password } = req.body;
//checking username exists
const existUsername = await User.findOne({ username: req.body.username});
if (existUsername) {
console.log('username taken');
}
});