amigo21
amigo21

Reputation: 391

Mongo find operation returns documents (objects). How to access this?

I search for a document in my mongo collection given a property value. I wish to save that document and spit out a property it contains. How can I go about this? I know it is very simple, but I must be doing something wrong

FYI, I am very new to mongo atm :) - using meteorjs

Here is the code:

var show = "The Walking Dead";
var TVShowObject = TVShow_List.find( {name: show} ); 
var channel_property = TVShowObject.channel;

and the mongo document is returned:

{ 
"_id": ObjectId("507f1f77bcf86cd799439011"),
"name": "The Walking Dead",
"channel": "AMC"
}

For some reason, the channel property is not being stored into channel_property variable. Any thoughts?

Upvotes: 1

Views: 68

Answers (2)

Radu Chiriac
Radu Chiriac

Reputation: 1424

What you should do is to use fetch() an array of Objects, if used after find(). Or if you expect only one result, in most cases findOne() is better.

var TVShowObject = TVShow_List.find( {name: show} ).fetch();

Upvotes: 0

saimeunt
saimeunt

Reputation: 22696

Collection.find returns a LocalCursor not a document, you need to use Collection.findOne :

var TVShowObject = TVShow_List.findOne( {name: show} );
// displays "AMC"
console.log(TVShowObject);

If the find operation is expected to return multiple documents, you need to use LocalCursor.forEach :

var cursor = TVShow_List.find({name:show});
cursor.forEach(function(tvShow){
  console.log(tvShow.channel);
});

Upvotes: 1

Related Questions