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

Databases Mongo Basics Understanding MongoDB Store Your Blog In Mongo

Stamos Bolovinos
Stamos Bolovinos
4,320 Points

Problem accessing field

Consider this query:

var id = db.posts.find()[0].author;

db.users.find(id)                       //works
db.users.find(id).signupDate            //returns nothing
db.users.find()[0].signupDate           //works

What is the problem of the second query? Why can I not access the document objects property signupDate?

1 Answer

db.users.find(id) will return an Array. So you need to declare the location of the array which is 0. Try db.users.find(id)[0].signupDate.

Neil McPartlin
Neil McPartlin
14,662 Points

Kanishkah is right. What confused me was Stamos's 3rd suggestion appearing to work until I realised all 6 authors have exactly the same signup timestamp. So although the declared 'id' belongs to Roger Riola, if the 3rd entry is rewritten as db.users.find()[0].name, this reveals that the signupDate actually belongs to Sam Lund.

db.users.find(id)[0].signupDate is correct and db.users.find(id)[0].name confirms it belongs to Roger Riola.