Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
dylan kane
2,772 PointsHow should I make a JS variable equal to a MongoDB field?
I need to make a JS variable equal to a MongoDB field, and as of now with the code I have, it is working, but not as intended. It is giving me a whole object, yet I only what the string value in which was assigned to the field. For example, you might have a document that contains the field
{name: "dylan"}
well I dont want all of that returned, I just want the string dylan. here is the code I have tried for my situation.
var game = SearchLobby.findOne( {profile: Meteor.userId()}, {game: 1,_id: 0} );
2 Answers

Wairton Rebouças
8,225 Pointsinstead of:
var game = SearchLobby.findOne( {profile: Meteor.userId()}, {game: 1,_id: 0} );
try this:
var name = SearchLobby.findOne( {profile: Meteor.userId()}).name;

Sean T. Unwin
28,686 PointsInclude .name
at the end.
var game = SearchLobby.findOne(
{profile: Meteor.userId()},
{game: 1,_id: 0}
).name;

dylan kane
2,772 Pointsim getting this error:
Exception in template helper: TypeError: Cannot read property 'name' of undefined
dylan kane
2,772 Pointsdylan kane
2,772 Pointswhy did you change the variable name to "name"? disregard my example {name: "dylan"} if that is why you are doing that, sorry if I created the misconception that it is relevant, it was just supposed to be an example.
Wairton Rebouças
8,225 PointsWairton Rebouças
8,225 Pointsjust use the same principle that I pointed out in the example replacing with the field you want
if it is name, game or foo just use name, game or foo :)
var field = SearchLobby.findOne( {your query parameters here}).foo;