0

I created an email checker function to verify if the email exists before registering a new user. I assigned req.body to user. However, the newUser function within my email checker function is not recognizing the variable user. How can I pass user into the function so if the email is not recognizing I can create the new user?

Here is my code:

app.post("/api/user", function(req, res) {

    var user = req.body;
    console.log("line 117", user);

    var searchUser = {
        email: user.email
    };

    User.findOne(searchUser, function(err, user){
        if (err) throw err;

        if (user) return res.status(401).send({
            message: "email already exists"
        });

        var newUser = new User({
            firstName: user.firstName,
            lastName: user.lastName,
            email: user.email,
            password: user.password
        });

        newUser.save(function(err) {
            createSendToken(newUser, res);

        });

    });

});
FormigaNinja
  • 1,571
  • 1
  • 24
  • 36
mtelford
  • 25
  • 2
  • 6
  • It looks like you're setting `user` in two different places. Maybe call the argument to that anonymous function something else? – Aaron Dufour Jul 22 '15 at 01:36
  • I just noticed your comment. Thanks for leaving a comment. There was a naming conflict with user and I was not passing it through correctly. – mtelford Jul 22 '15 at 01:36

1 Answers1

0

Here is my corrected code:

app.post("/api/user", function(req, res) {

var subscriber = req.body;

var searchUser = {
    email: subscriber.email
};

User.findOne(searchUser, subscriber, function(err, user){
    if (err) throw err;

    if (user) return res.status(401).send({
        message: "email already exists"
    });

    var newUser = new User({
        firstName: subscriber.firstName,
        lastName: subscriber.lastName,
        email: subscriber.email,
        password: subscriber.password
    });

    newUser.save(function(err) {
        createSendToken(newUser, res);

    });

});

});

mtelford
  • 25
  • 2
  • 6
  • It would be helpful if you described what you fixed rather than leaving us to have to do a visual diff to figure it out. – jfriend00 Jul 22 '15 at 02:06
  • Sorry about that. I replaced the name of the "user" variable to "subscriber". That way I could inject it into the findOne function to avoid the naming conflict I was having with the user parameter. – mtelford Jul 22 '15 at 02:19
  • 1
    Please use the "edit" button to add that to your answer. – jfriend00 Jul 22 '15 at 02:20