1

Background - I have a collection with 7,933 documents. I'm testing on a local host with a local mongodb server running. I also get the same issue on localhost with a remote mongodb server.

Problem - When running a simple db.collection.find().count(), meteor returns 0 documents found at first, incrementing to 7,933 over the course of about 6 seconds.

Console -

Count at: 1402440532060 is 0
Count at: 1402440533061 is 322
Count at: 1402440534064 is 1293
Count at: 1402440535087 is 2799
Count at: 1402440536557 is 4666
Count at: 1402440537696 is 7933
Count at: 1402440538697 is 7933
Count at: 1402440539699 is 7933
Count at: 1402440540701 is 7933
Count at: 1402440541702 is 7933 

App Structure -

/client/foo.html
/clint/foo.css
/client/foo.js
/lib/collections.js
/server/server.js

Code -

/lib/collections.js:

fooCollection = new Meteor.Collection('fooCollection');

/server/server.js:

Meteor.publish("fooDB", function () {
  return fooCollection.find();
});

/client/foo.js:

Deps.autorun(function() {
  Meteor.subscribe("fooDB");
});

var counter = 0;
var i = setInterval(function(){
    var ts = Date.now();
    console.log("Count at: " + ts + " is " + fooCollection.find().count());

    counter++;
    if(counter === 10) {
        clearInterval(i);
    }
}, 1000);
Adam
  • 3,142
  • 4
  • 29
  • 48
  • I've tested this with multiple collections. Also, running db.collection.find().count() in a mongo instance always returns the correct count. – Adam Jun 10 '14 at 23:22

1 Answers1

2

The data in the collection is being streamed from the server to the client. It won't teleport over there instantly. The client's local collection is just a cache or view of the server's publication, and is not an authoritative version of the database.

To make sure that your collection.count() is accurate, you'll want to make sure the subscription(s) sending data are ready. See the docs for http://docs.meteor.com/#meteor_subscribe.

Andrew Mao
  • 35,740
  • 23
  • 143
  • 224
  • Looks like I didn't do my homework. I should probably take care of counting on the server; use a meteor call to return the count; and not publish all documents to the client. – Adam Jun 10 '14 at 23:41
  • If you don't need to send all the documents to the client, you should definitely not do the count there! You can also send the count in a publication; see http://stackoverflow.com/q/14656567/586086. – Andrew Mao Jun 10 '14 at 23:56