0

To query objects on meteors client-side mongodb implementation, I can use either

MyModel.find();
// produces a lot of attributes, not useful

or

MyModel.find().fetch();
// returns array containing my objects from type 'MyModel', e.g.
// [ { _id: "1", title: "some title", url: "some Url"__proto__: Object }, .. ]

If I don't use fetch, I get a lot of attributes I don't understand and which doesn't seem to be useful for me. I wonder what actually happens when I call the fetch() method. I was not able to find any docs concerning this.

Ronin
  • 7,322
  • 6
  • 36
  • 54

2 Answers2

4

Collection.find();

It finds the documents in a collection that match the selector and returns the cursor. In Meteor, find() is synchronous, if something changes in database, it will get reflect on UI aswell.

Here is more details about Collection.find()

cursor.fetch();

fetch() is to get all records from database at-ones from cursor. You can use fetch on cursor returned by find(). When you use fetch(), you will get all records in an array but you will not gets updates, i.e. runtime database changes will not reflected on returned data after execution.

Here is more details about cursor.fetch()

What to use?

If you need all documents and want to do some operations on it, then only fetch() is useful else, working on cursor is best.

Conclusion

Using Collection.find() is best, reliable and lightweight. But finally it is as per your application logic.

Laxmikant Dange
  • 7,606
  • 6
  • 40
  • 65
1

There is one more fundamental difference between find and fetch to keep in mind: fetch causes a deep copy operation of the whole cursor data. That eats CPU and memory.

Thus: do not use fetch if you do not need it! You only need it when passing data to 3rd party libraries like d3 that do not understand what is a cursor and require a native JS array.

B M
  • 3,893
  • 3
  • 33
  • 47