expressJS + MongoDB - 登录/注册方法

expressJS + MongoDB - login/register method

本文关键字:注册 方法 登录 MongoDB expressJS      更新时间:2023-09-26

我想在我的expressJS API中使用登录/注册功能。所以现在我只是将密码和电子邮件插入我的数据库,我希望这个函数首先检查使用此电子邮件的用户是否已在数据库中 - 如果是,发送记录用户的响应。如果没有,只需将他插入数据库即可。是否可以在这里处理一些错误?

我已经有了:

exports.login = function(req, res){
var email = req.body.email;
var pwd = req.body.pass;
db.collection('users', function(err, collection) {
    collection.insert({login:email, password: pwd}, {safe:true}, function(err, result) {
      res.send("OK");
        });
    });
};'

也不知道接下来会发生什么。

您可以先尝试在数据库中查找用户。假设电子邮件是唯一的;

exports.login = function(req, res){
  var email = req.body.email;
  var pwd = req.body.pass;
  db.collection('users', function(err, collection) {
    if (err) return res.send(500, err);
    collection.findOne({login:email}, function(err, user) {
        // we found a user so respond back accordingly
        if (user) return res.send('user logged in');
        collection.insert({login:email, password: pwd}, {safe:true}, function(err, result) {
          if (err) return res.send(500, err);
          res.send("OK");
        });
    });
  });
};

请注意处理错误时res.send调用之前的return