如何检查用户名是否已存在于数据库集合MongoDB中



我在注册时发出后请求,但是如果用户名已被占用,我希望弹出错误。 有什么建议吗?

这是我的邮政路线:

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 将索引用户名并在插入之前对其进行检查。如果错误不是唯一的,则会引发错误。

您可以使用findOnemongoose方法

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');
}
});

最新更新