简体   繁体   English

在插入新用户之前尝试检查我的 mongodb 中是否存在用户(以防止多个相同的电子邮件注册)

[英]Trying to check if a user exist in my mongodb before inserting a new user (To prevent multiple same-email registration)

Using express.使用快递。 I am trying to create a .js file that handles POST request looking to check if a user is existing before inserting to my MongoDB.我正在尝试创建一个处理 POST 请求的 .js 文件,以在插入到我的 MongoDB 之前检查用户是否存在。 I built 2 MongoClient connection to handle different cases.我建立了 2 个 MongoClient 连接来处理不同的情况。 first is to check if a user exist.首先是检查用户是否存在。 If a user does not exist then it would go to the second connection.如果用户不存在,那么它将转到第二个连接。 I can't comprehend what i am doing wrong我无法理解我做错了什么

Code is :`代码是:`

router.post('/', function(req, res, next) {
  console.log("inside post method profile")
  ssn = req.session;
  ssn.firstName = req.body.fname;
  ssn.lastName = req.body.lname;
  ssn.userEmail = req.body.email;
  ssn.userPass = req.body.pass;
  let userExists = false;

  MongoClient.connect(url, function(err, db) {
    if (err) throw err;
    let dbo = db.db("projectOne");
    let myInfoLog = {
      email: ssn.userEmail,
      pass: ssn.userPass
    };

    // TRYING TO COUNTERCHECK IF A USER ALREADY EXISTS
    dbo.collection("userInfo").findOne(myInfoLog, function(err, data) {
      if (data.email) {
        userExists = true;
        ssn.signUpError = "User email already exists";
        console.log("data returns an active email");
        db.close();
        res.redirect('/');
      }
    });
  });

  if (userExists == false) {
    MongoClient.connect(url, function(err, db) {
      if (err) throw err;
      let dbo = db.db("projectOne");
      let myInfoLog = {
        email: ssn.userEmail,
        pass: ssn.userPass
      };

      let myInfo = {
        fname: ssn.firstName,
        lname: ssn.lastName,
        email: ssn.userEmail,
        pass: ssn.userPass
      };
      dbo.collection("userInfo").insertOne(myInfo, function(err, data) {
        if (err) throw err;
        console.log("collection inserted");
        // console.log(data.ops[0].fname);
        // console.log(data.ops[0].lname);
        // console.log(data.ops[0].email);
        // console.log(data.ops[0].pass);

        ssn.firstName = data.ops[0].fname;
        ssn.lastName = data.ops[0].lname;
        ssn.userEmail = data.ops[0].email;
        ssn.userPass = data.ops[0].pass;
        console.log("welcome! " + ssn.firstName + " " + ssn.lastName)

        db.close();
      });

      res.redirect('/profile');

    });
  }

});

module.exports = router;

I am getting an error :我收到一个错误:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:485:11)
at ServerResponse.header (C:\Users\rousb\Desktop\Internship2020\P_01\node_modules\express\lib\response.js:767:10)
at ServerResponse.location (C:\Users\rousb\Desktop\Internship2020\P_01\node_modules\express\lib\response.js:884:15)
at ServerResponse.redirect (C:\Users\rousb\Desktop\Internship2020\P_01\node_modules\express\lib\response.js:922:18)
at C:\Users\rousb\Desktop\Internship2020\P_01\routes\profile.js:47:15
at executeCallback (C:\Users\rousb\Desktop\Internship2020\P_01\node_modules\mongodb\lib\operations\execute_operation.js:70:5)
at handleCallback (C:\Users\rousb\Desktop\Internship2020\P_01\node_modules\mongodb\lib\utils.js:128:55)
at C:\Users\rousb\Desktop\Internship2020\P_01\node_modules\mongodb\lib\operations\find_one.js:29:9
at C:\Users\rousb\Desktop\Internship2020\P_01\node_modules\mongodb\lib\utils.js:731:5
at C:\Users\rousb\Desktop\Internship2020\P_01\node_modules\mongodb\lib\cursor.js:251:9 {

code: 'ERR_HTTP_HEADERS_SENT'代码:'ERR_HTTP_HEADERS_SENT'

You're executing 2 asynchronous actions at the same time.您正在同时执行 2 个异步操作。 They both end up trying to res.redirect('...');他们最终都试图res.redirect('...'); You can't redirect once the user has already been redirected.一旦用户已被重定向,您就无法重定向。 Your if (userExists == false) { is executed before you do the check in the block above.您的if (userExists == false) {在您执行上述块中的检查之前执行。

You could chain your callbacks like this:你可以像这样链接你的回调:

router.post('/', function(req, res, next) {
  ssn = req.session;
  ssn.firstName = req.body.fname;
  ssn.lastName = req.body.lname;
  ssn.userEmail = req.body.email;
  ssn.userPass = req.body.pass;

  MongoClient.connect(url, function(err, db) {
    if (err) throw err;
    let dbo = db.db("projectOne");
    let myInfoLog = {
      email: ssn.userEmail // Don't include the password!
    };

    // Check if email exists
    dbo.collection("userInfo").findOne(myInfoLog, function(err, data) {
      if (data.email) {
        ssn.signUpError = "User email already exists";
        console.log("data returns an active email");
        db.close();
        res.redirect('/');
      } else {
        const myInfo = {
          fname: ssn.firstName,
          lname: ssn.lastName,
          email: ssn.userEmail,
          pass: ssn.userPass
        };
        // Insert user
        dbo.collection("userInfo").insertOne(myInfo, function(err, data) {
          if (err) throw err;
          console.log("collection inserted");

          ssn.firstName = data.ops[0].fname;
          ssn.lastName = data.ops[0].lname;
          ssn.userEmail = data.ops[0].email;
          ssn.userPass = data.ops[0].pass;
          console.log("welcome! " + ssn.firstName + " " + ssn.lastName);
          db.close();
          res.redirect('/profile');
        });
      }
    });
  });
});

module.exports = router;

You should move your if (userExists == false) { block into the first lookup.您应该将if (userExists == false) {块移动到第一次查找中。

dbo
  .collection("userInfo")
  .findOne(myInfoLog, function(err, data) {
    if (data.email) {
      // handle case where user already exists
    } else {
      // handle case where user doesn't exist yet
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 保存用户前如何检查电子邮件是否存在 - How to check if email exist before save the user 如何防止新用户在 Firebase 上注册? - How to prevent new user registration on Firebase? 如何在Meteor中检查用于用户注册的电子邮件 - How to Check an Email Used for User Registration in Meteor 检查 MongoDB 中是否已存在用于注册的用户名/电子邮件的有效方法 - Efficient way to check if username/email already exist in MongoDB for registration 要检查用户是否已经存在MongoDB - Want to check if user already exist MongoDB 在导航到新页面之前检查 firebase 数据库中是否存在用户身份验证 ID - Check if user auth id exist in firebase database before navigating to a new page 在使用 MySQL 创建新用户并续集之前生成自定义唯一 id 并检查它不存在 - Generate a custom unique id and check it does not exist before creating a new user with MySQL and sequelize 当他们选中一个复选框时试图拉用户 email - Trying to pull user email when they check a checkbox 如何使用Codeinighter和Ajax检查用户表中是否存在电子邮件 - How to I check if email exist in user table with codeinighter and ajax 检查电子邮件是否已经存在错误未定义索引:user_id - Check if email already exist error undefined index: user_id
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM