1

In my nodejs project I'm fetching data from my MongoDB and retrieve after querying with this code:

app.get('/:user_id', (req, res) => {
  Contact.findById(req.params.user_id, function (err, user) {
    if (err){
        res.send(err);
    }
    let user_temp = JSON.stringify(user)
    console.log("1 - ", user);
    console.log("2 - ", user.name);
    console.log("3 - ", user_temp)
    console.log("4 - ", user_temp.phone);
    res.render('userInfo', {user: user})
  });  
}) 

The log I get is this

1 -  {
  _id: 5f56a47d5a246e5ff8b67129,
  name: 'UserA',
  phone: '054523423',
  __v: 0
}
2 -  undefined
3 -  {"_id":"5f56a47d5a246e5ff8b67129","name":"UserA","phone":"054523423","__v":0}
4 -  undefined

When I'm trying to console.log those values before or after JSON.stringify I always get undefined. I've looked at other bugs and I can't seem to find an explanation. What am I doing wrong?

3
  • let user_temp = JSON.stringify(user) before his line what does typeof user give? I guess it is the string that's why it is undefined Commented Sep 10, 2020 at 17:45
  • @aRvi it's an object Commented Sep 10, 2020 at 17:47
  • 1
    tip: use if (err) return res.send(err) else /foo will break with various errors Commented Sep 10, 2020 at 18:00

1 Answer 1

1

Ohh now I get it. It was a mongoose problem. Since I did not define name in the Contact schema but rather username, the mongoose apparently could not interpret the Object.key notation. I've changed my Contact model Scheme and now it works!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.