Search code examples
mongodbmeteorfetchminimongo

what happens when I execute fetch() on minimongo


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.


Solution

  • 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.