1

I want to have login/register function in my expressJS API. So now im just inserting password and email into my database, i want this function to first check if user with this email is already in database - if yes, send response that user is logged. If not, just insert him to database. Is it possible to handle some errors in here?

I already have it:

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");
        });
    });
};\

and dont know what's next.

Chris Laplante
  • 29,338
  • 17
  • 103
  • 134
pawel
  • 5,976
  • 15
  • 46
  • 68

1 Answers1

0

You can first try to find the user in your database. Assuming email is unique;

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

notice the return's before the res.send calls when handling errors.

Bulkan
  • 2,555
  • 1
  • 20
  • 31
  • even if im typing the same email, it still inserts new document - are u sure that these conditions are good? I mean `if(user)` works in javascript? :) – pawel Nov 04 '13 at 17:11
  • should've added @Bulkan i think :) – pawel Nov 04 '13 at 20:38
  • @pawel using [mongoskin](https://github.com/kissjs/node-mongoskin) the callback passed to `findOne` is called with two arguments `err` and the `value` from the DB. If the query doesn't match anything then the `value` is set to _null_. In JavaScript [null](http://stackoverflow.com/a/5486264/1048697) is a _falsy_ value. – Bulkan Nov 05 '13 at 01:51