Meteor.Collection and Meteor.Collection.Cursor

meteor, mongodb

Solution

Did new Meteor.Collection("name") create a MONGODB collection with the parameter name?

Not exactly. A `Meteor.Collection` represents a MongoDB collection that may or may not exist yet, but the actual MongoDB collection isn't actually created until you insert a document.

A `Meteor.Collection.Cursor` is a reactive data source that represents a changing subset of documents that exist within a MongoDB collection. This subset of documents is specified by the `selector` and `options` arguments you pass to the `Meteor.Collection.find(selector, options)` method. This `find()` method returns the cursor object. I think the Meteor Docs explain cursors well:

`find` returns a cursor. It does not immediately access the database or return documents. Cursors provide fetch to return all matching documents, map and forEach to iterate over all matching documents, and observe and observeChanges to register callbacks when the set of matching documents changes.

Collection cursors are not query snapshots. If the database changes between calling Collection.find and fetching the results of the cursor, or while fetching results from the cursor, those changes may or may not appear in the result set.

Cursors are a reactive data source. The first time you retrieve a cursor's documents with fetch, map, or forEach inside a reactive computation (eg, a template or autorun), Meteor will register a dependency on the underlying data. Any change to the collection that changes the documents in a cursor will trigger a recomputation. To disable this behavior, pass {reactive: false} as an option to find.

The reactivity of cursors is important. If I have a cursor object, I can retrieve the current set of documents it represents by calling `fetch()` on it. If the data changes in between calls, the `fetch()` method will actually return a different array of documents. Many things in Meteor natively understand the reactivity of cursors. This is why we can return a cursor object from a template helper function:

Template.foo.documents = function() {
  return MyCollection.find(); // returns a cursor object, rather than an array of documents
};

Behind the scenes, Meteor's templating system knows to call `fetch()` on this cursor object. When the server sends the client updates telling it that the collection has changed, the cursor is informed of this change, which causes the template helper to be recomputed, which causes the template to be rerendered.

Problem

What is ``` Meteor.Collection ``` and ``` Meteor.Collection.Cursor ``` ? How does these two related to each other? Did: ``` new Meteor.Collection("name") ``` create a `MONGODB` collection with the parameter name?

Original source