如何验证MongoDB中是否已有电子邮件的NodeJS

问题描述 投票:-1回答:1

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

如果电子邮件已经存在于数据库中,如何验证错误消息?

node.js mongodb passport.js body-parser
1个回答
0
投票

您可以使用指定的电子邮件在集合上调用findOne。如果没有文件匹配,它会解析为null。您可以使用它来检测数据库中是否已存在具有相同电子邮件的用户。

您没有提供相关的代码部分来猜测数据库的体系结构,但您可能会使用以下内容:

const { MongoClient } = require('mongodb');
const email = '[email protected]';

// 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...
  }

})()
© www.soinside.com 2019 - 2024. All rights reserved.