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! While you're at it, check out some resources Treehouse students have shared here.

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

JavaScript

dylan kane
dylan kane
2,772 Points

How 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
Wairton Rebouças
8,225 Points

instead of:

var game = SearchLobby.findOne( {profile: Meteor.userId()}, {game: 1,_id: 0} );

try this:

var name = SearchLobby.findOne( {profile: Meteor.userId()}).name;
dylan kane
dylan kane
2,772 Points

why 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
Wairton Rebouças
8,225 Points

just 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;

Sean T. Unwin
Sean T. Unwin
28,690 Points

Include .name at the end.

var game = SearchLobby.findOne(
  {profile: Meteor.userId()},
  {game: 1,_id: 0}
).name;
dylan kane
dylan kane
2,772 Points

im getting this error:

Exception in template helper: TypeError: Cannot read property 'name' of undefined