Eugene Goldberg
Eugene Goldberg

Reputation: 15534

meteor app: how to properly retrieve a single document from a collection on the client

In my meteor app I'm storing the client's unique id string in a collection called UserNavigationTracker:

{
    "clientId" : "xxNfxxPGi7tqTbxc4",
    "currentWizard" : "IntroductionWizard",
    "currentStep" : "Step-1",
    "_id" : "ifBJ688upEMfzzviC"
}

As a part of the app initialization, I need to check and see if information about my client is already stored in the database. I'm struggling with retrieving this record back from the collection. Here is what I'm doing:

var clientIdInDatabase = UserNavigationTrackerCollection.find({"clientId": "xxNfxxPGi7tqTbxc4"});
console.log('clientIdInDatabase:  ' + clientIdInDatabase);

The browser console output from this is: clientIdInDatabase: [object Object]

Mt question is: how can I get the actual value of the clientId field from this returned Object?

Upvotes: 0

Views: 340

Answers (1)

David Weldon
David Weldon

Reputation: 64312

find returns a cursor, just replace it with findOne to get a single object (or undefined). If you ever want to get more than one document, you can get an array of them with find(...).fetch(). You can read the documentation for all of these functions in this section of the docs.


Based on our discussion, this may work on the client to compensate for the subscription delay:

Tracker.autorun(function() {
  var clientId = Session.get('clientId');
  var unt = UserNavigationTrackerCollection.findOne({clientId: clientId});
  Session.set('isClientIdInDatabase', unt != null);
});

Note this assumes that clientId and isClientIdInDatabase are stored in session variables.

Upvotes: 1

Related Questions