Alejandro Baltra
Alejandro Baltra

Reputation: 68

Can't retrieve object property in Javascript

Currently, I'm trying to retrieve a particular property from a javascript object returned by mongoose. I can see the property when printing the whole object, but when trying to use it, I get an undefined. Here's the code:

Match.findOne({id: match.id}, function (err, match) {
    console.log(match)
    console.log(typeof match)
    console.log(match.id)
    console.log(match.winner)
})

The output of that is:

{ _id: 552c7f2925efcbc88ccc55bf,
    id: 499142595,
    region: 'br',
    winner: 200,
    championsLose: [ 25, 96, 81, 113, 63 ],
    championsWin: [ 37, 238, 201, 268, 81 ] 
}
object
499142595
undefined

Even though the 'winner' property is clearly there. Any ideas?

UPDATE: added more logging to the above code and results of it

Upvotes: 3

Views: 140

Answers (3)

Alejandro Baltra
Alejandro Baltra

Reputation: 68

Finally the issue wasn't in that piece of code, but in the Model definition. The variable name wasn't updated properly, so the old name was still being used there:

var mongoose = require('mongoose');

module.exports = mongoose.model('Match',{
    id: Number,
    region: String,
    championsWin: Array,
    championsLose: Array,
    winnerTeamId: Number
});

And the proper model should be:

module.exports = mongoose.model('Match',{
    id: Number,
    region: String,
    championsWin: Array,
    championsLose: Array,
    winner: Number
});

Thanks a lot for the help!

Upvotes: 0

A.B
A.B

Reputation: 20455

console updates("Live Update") the last references if the object/property is change even after console.log(). i have recently got this pain using chrome

it might be the case

check this example in chrome, dont know how this problem behaves in node console or the tool you are using

obj = {a:"b",b:"c"};
console.log(obj);  // logs Object { b: "c" } not {a:"b",b:"c"}
delete obj.a;
console.log(obj);// logs Object { b: "c" }

you might have deleted the match.winner property later in the code. that seems to be the case only

Upvotes: 0

dave
dave

Reputation: 64725

It's odd that there are no quotes around the value of associated with the key "_id":

{ _id: 552c7f2925efcbc88ccc55bf, // should be --> "552c7f2925efcbc88ccc55bf" 
id: 499142595,
region: 'br',
winner: 200,
championsLose: [ 25, 96, 81, 113, 63 ],
championsWin: [ 37, 238, 201, 268, 81 ] 
}

This seems to indicate that it is not actually an object. Which, of course, explains why match.winner is undefined. I would do console.log(typeof match) and see what it says.

Upvotes: 2

Related Questions