我在nodejs中创建了一个loginapp,但我想验证数据库中是否已存在电子邮件(或用户名)。
router.post('/register', function(req, res) {
var name = req.body.name;
var email = req.body.email;
var username = req.body.username;
var password = req.body.password;
var password2 = req.body.password2;
req.checkBody('username', 'Please enter a username').notEmpty();
req.checkBody('email', 'pls enter a email adress').notEmpty().isEmail();
req.checkBody('password', 'pls enter a password').notEmpty();
req.checkBody('password2', 'the password dont match').equals(req.body.password);
var errors = req.validationErrors();
if(errors) {
res.render('register',{
errors:errors,
})
} else {
var newUser = new User({
email:email,
username: username,
password: password
});
User.createUser(newUser, function(err, user){
if(err) throw err;
console.log(user);
});
req.flash('success_msg', 'u create an accoun, u can log');
res.redirect('/users/login');
}
})
如果电子邮件已经在数据库中,怎么办才能验证为什么出现错误消息?
答案 0 :(得分:0)
您可以使用指定的电子邮件地址致电收藏集上的findOne。如果没有文档匹配,它将解析为null
。您可以使用,以检测是否存在与数据库中的同一个电子邮件地址的用户。
您没有提供代码的相关部分来猜测数据库的体系结构,但是您可能会使用类似以下的内容:
const { MongoClient } = require('mongodb');
const email = 'john@doe.com';
// wraps everything in an async function
(async () => {
// connect to database
const client = new MongoClient('mongodb://localhost:27017');
await client.connect();
const users = client.db('your-db-name').collection('users');
// look for an existing user
let possibleDuplicate = await users.findOne({email});
if (possibleDuplicate===null) {
// email is not taken
// do something...
} else {
// email is taken
// do something...
}
})()