1

The query to the database returns the correct object but I'm having trouble accessing the values of the members of the object.

Here's my code:

socket.on("getUser", function(username){
    User.find({username: username}, function (err, user)
    {
        console.log("*** " + user + " \n*** " + typeof user);
        console.log(user.username);

        if (err) console.log(err);
        else {
            socket.emit("getUserResponse", user);
        }
    })
});

The output from this is:

*** { ticketsPurchased: [],
  _id: 5add436fb3da1931c8a64de6,
  username: 'nekumes@emailure.net',
  password: 'test',
  firstName: 'abc',
  lastName: 'abd',
  admin: false,
  __v: 0 } 
*** Type = object
*** undefined

Why can't I access the value of username? It works fine when I output the user object. Please help!

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
Sandy Leach
  • 75
  • 10
  • This can be an issue where the variable is a string, you may have to parse it before accessing the variables inside it. Parse the data with JSON.parse(), and the data becomes a JavaScript object. Example - const userJson = JSON.parse(user); Try this out – Meet Dave Apr 23 '18 at 03:42
  • 1
    Also remember that `.find()` returns an "array". If you expect **one** result then you really want `findOne()` or `console.log(user[0].username)` – Neil Lunn Apr 23 '18 at 03:46

0 Answers0