sohel khalifa
sohel khalifa

Reputation: 5588

Accessing MongoDB collection values in JavaScript

I am new in Meteor, and especially in MongoDB.

I have googled a lot regarding this issue but nothing found related to this.

So there is an app that contains two collections: EventsCollection and RacesCollection and runs on Meteor server.

The RacesCollection has number of records like:

RacesCollection.insert({raceId:"r1", eventId:"e1", raceName:"Moto race 1", status:"statusDetail", mode:"modeDetail"});
RacesCollection.insert({raceId:"r2", eventId:"e1", raceName:"Moto race 2", status:"statusDetail", mode:"modeDetail"});

This is the resultant collection which contains rows having eventId = e1

var race = RacesCollection.find({eventId: "e1"});

Now what i want to do is to simply access the fields of race into javascript, something like race.raceId, race.raceName. How to implement this? Is there any getter method for accessing particular data field?

And how to iterate through multiple rows of race in case it contains number of rows?

Any recommendation will be appriciated.

Upvotes: 14

Views: 16293

Answers (4)

mkimmet
mkimmet

Reputation: 769

Sekai's answer works, however, it's written from a MongoDB perspective. From a Meteor JavaScript helper, using the variables used in the question, it would look like:

RacesCollection.find(
   {eventId: "e1"}
).forEach(function(race){
   console.log( race.raceName );
};

Upvotes: 4

Aysennoussi
Aysennoussi

Reputation: 3860

use ForEach :

db.databaseName.find(
  {
    field:"valueofField"
  }
).forEach(function(obj){
    print(obj.fieldname)
})

Upvotes: 31

Racing Tadpole
Racing Tadpole

Reputation: 4370

I just had the same problem and hasNext() did not work for me.

Instead Meteor provides fetch() to convert a cursor to a javascript array. So you can use:

var raceCursor = RacesCollection.find({eventId: "e1"});
var races = raceCursor.fetch();
for (var i=0; i<races.length; i++) {
    console.log( races[i].raceName );
}

Upvotes: 4

shelman
shelman

Reputation: 2699

MongoDB's find() method returns what's called a "cursor". In javascript, you can iterate over the cursor as in these docs, and access the fields of the documents using standard javascript property access.

For example (untested code, but this is the idea):

var raceCursor = RacesCollection.find({eventId: "e1"});
var race;
while ( raceCursor.hasNext() ) {
    race = raceCursor.next();
    console.log( race.raceName );
}

Since Meteor is pure javascript, it also supports using forEach() to iterate over the cursor's documents, as in this example.

Upvotes: 10

Related Questions