Klian
Klian

Reputation: 1565

Getting email with mongoose, always undefined

I'm using mongoose in my nodejs/express project.

I have a login form and I want to retrieve the email field, but I always get a "undefined" value.

This is my code:

User.findOne({ email: email, pass: pass }, function(err, user_data){
        if (err) return handleError(err);
        if(user_data){
            req.session.user_id = user_data._id;
            req.session.email = user_data.email;
            console.log(user_data);
            console.log("the email: " + user_data.email);
            console.log("the name: " + user_data.name);
            res.redirect('/');
        }else{
            res.redirect('/login');
        }
    });

The output:

{ _id: 534038aca4198a8fcf0001ac,
  name: 'My name',
  email: '[email protected]',
  pass: '098f6bcd4621d373cade4e832627b4f6' }

The email: undefined
The name: My name

What is wrong with the email field ?

Thanks

Upvotes: 1

Views: 110

Answers (1)

Daniel Selga
Daniel Selga

Reputation: 11

I had the same error and i solve creating a new object from the response of the mongoose query.

exports.getUser = async (req, res) => {
    try {
        const user = await User.findOne({email: email, pass: pass})
        const userParams = {...user}
        const email = userParams._doc.email
        console.log(email)
    } catch(err) {
        console.log(err)
    }
}

I don't recommend you to use this method to auth users, please check auth0 or Oauth2.

Upvotes: 1

Related Questions