Emir Kutlugün
Emir Kutlugün

Reputation: 447

user.email become undefined in Node.js mongo

Our backend was deployed on Heroku and running without error until today but 2-3 hours ago our servers started to give crash, and the reason is our function below can't read property 'email' of user and prints undefined. No idea why this is happening suddenly. First, I thought it was related to the server but I'm getting the same result in localhost too. As i said before code was working literally 2-3 hours ago.

findMe function

exports.findMe = (req, res) => {
  User.findOne(
    { _id: req.userData.userId },
    { email: 0, password: 0 },
    (err, user) => {
      if (err) {
        return res.status(500).json({
          ...err,
        });
      }
      console.log(user.email);
      const expires = "10y";
      const token = jwt.sign(
        {
          email: user.email,
          userId: user._id,
          username: user.username,
          committeeId: user.committeeId,
          role: user.role,
        },
        process.env.JWT_KEY,
        {
          expiresIn: expires,
        }
      );
      return res.status(200).json({
        user: user,
        token: token,
      });
    }
  );
};

Output of code above

{
    "user": {
        "education": {
            "university": "YILDIZ TEKNİK ÜNİVERSİTESİ",
            "department": "MATEMATİK MÜHENDİSLİĞİ",
            "year": 3
        },
        "oldCommittees": {
            "committeeId": null,
            "title": null,
            "year": null,
            "date": "2021-08-28T21:53:48.992Z"
        },
        "isVerified": true,
        "bio": null,
        "photo": null,
        "photoSm": null,
        "photoXs": null,
        "phoneNo": null,
        "committeeId": "5d9360e99b572100172cc581",
        "title": "CS Başkanı",
        "role": 0,
        "blockedUsers": [],
        "_id": "5d9362ec9b572100172cc648",
        "name": "Emir",
        "surname": "Kutlugün",
        "username": "emir-kutlugun2",
        "date": "2019-10-01T14:30:04.884Z",
        "__v": 0
    },
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI1ZDkzNjJlYzliNTcyMTAwMTcyY2M2NDgiLCJ1c2VybmFtZSI6ImVtaXIta3V0bHVndW4yIiwiY29tbWl0dGVlSWQiOiI1ZDkzNjBlOTliNTcyMTAwMTcyY2M1ODEiLCJyb2xlIjowLCJpYXQiOjE2MzAxODc2MzEsImV4cCI6MTk0NTc2MzYzMX0.Jjl_-mXN2Ozn96yJpqNPYPFl3mngnZ4N_I8KYBNYCoo"
}

console.log(user.email) logs undefined

Upvotes: 0

Views: 128

Answers (1)

Montgomery Watts
Montgomery Watts

Reputation: 4034

This code:

User.findOne(
    { _id: req.userData.userId },
    { email: 0, password: 0 },

Uses mongoose's Model.findOne() method. The first parameter, { _id: req.userData.userId } is a document containing the conditions you want the document returned to match.

The second parameter, { email: 0, password: 0 } is the projection. This tells MongoDB which fields should be included in the result. The projection in your code is an example of returning all fields but excluded fields. The document you get back from this operation will have every field except email and password.

If you want to include email in the result for later use, you will need to remove it from this projection. You could change the projection to { password: 0 }, so the email field is included and the password field is still excluded.

Put together, it may look like this:

User.findOne(
    { _id: req.userData.userId },
    { password: 0 },

Upvotes: 1

Related Questions