Collections

Documentation on how to use Meteor's database collections.

Meteor stores data in collections. To get started, declare acollection with new Mongo.Collection.

Anywhere

new Mongo.Collection(name, [options])

import { Mongo } from 'meteor/mongo' (mongo/collection.js, line 27)

Constructor for a Collection

Arguments

  • nameString
  • The name of the collection. If null, creates an unmanaged (unsynchronized) local collection.

Options

  • connectionObject
  • The server connection that will manage this collection. Uses the default connection if not specified. Pass the return value of calling DDP.connect to specify a different server. Pass null to specify no connection. Unmanaged (name is null) collections cannot specify a connection.

  • idGenerationString

  • The method of generating the _id fields of new documents in this collection. Possible values:

    • 'STRING': random strings
    • 'MONGO': random Mongo.ObjectID valuesThe default id generation technique is 'STRING'.
  • transformFunction

  • An optional transformation function. Documents will be passed through this function before being returned from fetch or findOne, and before being passed to callbacks of observe, map, forEach, allow, and deny. Transforms are not applied for the callbacks of observeChanges or to cursors returned from publish functions.

  • defineMutationMethodsBoolean

  • Set to false to skip setting up the mutation methods that enable insert/update/remove from client code. Default true.

Calling this function is analogous to declaring a model in a traditional ORM(Object-Relation Mapper)-centric framework. It sets up a collection (a storagespace for records, or “documents”) that can be used to store a particular typeof information, like users, posts, scores, todo items, or whatever matters toyour application. Each document is a EJSON object. It includes an _idproperty whose value is unique in the collection, which Meteor will set when youfirst create the document.

  1. // Common code on client and server declares a DDP-managed Mongo collection.
  2. const Chatrooms = new Mongo.Collection('chatrooms');
  3. const Messages = new Mongo.Collection('messages');

The function returns an object with methods to insertdocuments in the collection, update their properties, andremove them, and to find the documents in thecollection that match arbitrary criteria. The way these methods work iscompatible with the popular Mongo database API. The same database APIworks on both the client and the server (see below).

  1. // Return an array of my messages.
  2. const myMessages = Messages.find({ userId: Meteor.userId() }).fetch();
  3. // Create a new message.
  4. Messages.insert({ text: 'Hello, world!' });
  5. // Mark my first message as important.
  6. Messages.update(myMessages[0]._id, { $set: { important: true } });

If you pass a name when you create the collection, then you aredeclaring a persistent collection — one that is stored on theserver and seen by all users. Client code and server code can bothaccess the same collection using the same API.

Specifically, when you pass a name, here’s what happens:

  • On the server (if you do not specify a connection), a collection with thatname is created on a backend Mongo server. When you call methods on thatcollection on the server, they translate directly into normal Mongo operations(after checking that they match your access control rules).

  • On the client (and on the server if you specify a connection), a Minimongoinstance is created. Minimongo is essentially an in-memory, non-persistentimplementation of Mongo in pure JavaScript. It serves as a local cache thatstores just the subset of the database that this client is working with. Queries(find) on these collections are served directly out of this cache,without talking to the server.

  • When you write to the database on the client (insert,update, remove), the command is executed locallyimmediately, and, simultaneously, it’s sent to the server and executedthere too. This happens via stubs, because writes areimplemented as methods.

When, on the server, you write to a collection which has a specifiedconnection to another server, it sends the corresponding method to the otherserver and receives the changed values back from it over DDP. Unlike on theclient, it does not execute the write locally first.

If you pass a name to a client-only collection, it will not be synchronizedwith the server and you need to populate the collection “manually” using thelow-level publication interface (added/changed/removed).See added for more information.

If you pass null as the name, then you’re creating a localcollection. It’s not synchronized anywhere; it’s just a local scratchpadthat supports Mongo-style find, insert,update, and remove operations. (On both theclient and the server, this scratchpad is implemented using Minimongo.)

By default, Meteor automatically publishes every document in yourcollection to each connected client. To turn this behavior off, removethe autopublish package, in your terminal:

  1. meteor remove autopublish

and instead call Meteor.publish to specify which parts ofyour collection should be published to which users.

  1. // Create a collection called `Posts` and put a document in it. The document
  2. // will be immediately visible in the local copy of the collection. It will be
  3. // written to the server-side database a fraction of a second later, and a
  4. // fraction of a second after that, it will be synchronized down to any other
  5. // clients that are subscribed to a query that includes it (see
  6. // `Meteor.subscribe` and `autopublish`).
  7. const Posts = new Mongo.Collection('posts');
  8. Posts.insert({ title: 'Hello world', body: 'First post' });
  9. // Changes are visible immediately—no waiting for a round trip to the server.
  10. assert(Posts.find().count() === 1);
  11. // Create a temporary, local collection. It works just like any other collection
  12. // but it doesn't send changes to the server, and it can't receive any data from
  13. // subscriptions.
  14. const Scratchpad = new Mongo.Collection;
  15. for (let i = 0; i < 10; i += 1) {
  16. Scratchpad.insert({ number: i * 2 });
  17. }
  18. assert(Scratchpad.find({ number: { $lt: 9 } }).count() === 5);

Generally, you’ll assign Mongo.Collection objects in your app to globalvariables. You can only create one Mongo.Collection object for eachunderlying Mongo collection.

If you specify a transform option to the Collection or any of its retrievalmethods, documents are passed through the transform function before beingreturned or passed to callbacks. This allows you to add methods or otherwisemodify the contents of your collection from their database representation. Youcan also specify transform on a particular find, findOne, allow, ordeny call. Transform functions must return an object and they may not changethe value of the document’s _id field (though it’s OK to leave it out).

  1. // An animal class that takes a document in its constructor.
  2. class Animal {
  3. constructor(doc) {
  4. _.extend(this, doc);
  5. }
  6. makeNoise() {
  7. console.log(this.sound);
  8. }
  9. }
  10. // Define a collection that uses `Animal` as its document.
  11. const Animals = new Mongo.Collection('animals', {
  12. transform: (doc) => new Animal(doc)
  13. });
  14. // Create an animal and call its `makeNoise` method.
  15. Animals.insert({ name: 'raptor', sound: 'roar' });
  16. Animals.findOne({ name: 'raptor' }).makeNoise(); // Prints 'roar'

transform functions are not called reactively. If you want to add adynamically changing attribute to an object, do it with a function that computesthe value at the time it’s called, not by computing the attribute at transformtime.

In this release, Minimongo has some limitations:

  • $pull in modifiers can only accept certain kindsof selectors.
  • findAndModify, aggregate functions, andmap/reduce aren’t supported.

All of these will be addressed in a future release. For fullMinimongo release notes, see packages/minimongo/NOTESin the repository.

Minimongo doesn’t currently have indexes. It’s rare for this to be anissue, since it’s unusual for a client to have enough data that anindex is worthwhile.

Read more about collections and how to use them in the Collections article in the Meteor Guide.

Anywhere

Mongo.Collection#find([selector], [options])

(mongo/collection.js, line 309)

Find the documents in a collection that match the selector.

Arguments

Options

  • sortMongo Sort Specifier
  • Sort order (default: natural order)

  • skipNumber

  • Number of results to skip at the beginning

  • limitNumber

  • Maximum number of results to return

  • fieldsMongo Field Specifier

  • Dictionary of fields to return or exclude.

  • reactiveBoolean

  • (Client only) Default true; pass false to disable reactivity

  • transformFunction

  • Overrides transform on the Collection for this cursor. Pass null to disable transformation.

  • disableOplogBoolean

  • (Server only) Pass true to disable oplog-tailing on this query. This affects the way server processes calls to observe on this query. Disabling the oplog can be useful when working with data that updates in large batches.

  • pollingIntervalMsNumber

  • (Server only) When oplog is disabled (through the use of disableOplog or when otherwise not available), the frequency (in milliseconds) of how often to poll this query when observing on the server. Defaults to 10000ms (10 seconds).

  • pollingThrottleMsNumber

  • (Server only) When oplog is disabled (through the use of disableOplog or when otherwise not available), the minimum time (in milliseconds) to allow between re-polling when observing on the server. Increasing this will save CPU and mongo load at the expense of slower updates to users. Decreasing this is not recommended. Defaults to 50ms.

  • maxTimeMsNumber

  • (Server only) If set, instructs MongoDB to set a time limit for this cursor's operations. If the operation reaches the specified time limit (in milliseconds) without the having been completed, an exception will be thrown. Useful to prevent an (accidental or malicious) unoptimized query from causing a full collection scan that would disrupt other database users, at the expense of needing to handle the resulting error.

  • hintString or Object

  • (Server only) Overrides MongoDB's default index selection and query optimization process. Specify an index to force its use, either by its name or index specification. You can also specify { $natural : 1 } to force a forwards collection scan, or { $natural : -1 } for a reverse collection scan. Setting this is only recommended for advanced users.

find returns a cursor. It does not immediately access the database or returndocuments. Cursors provide fetch to return all matching documents, map andforEach to iterate over all matching documents, and observe andobserveChanges to register callbacks when the set of matching documentschanges. Cursors also implement ES2015’s iteration protocols.

Collection cursors are not query snapshots. If the database changesbetween calling Collection.find and fetching theresults 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. On the client, the first time you retrieve acursor’s documents with fetch, map, or forEach inside areactive computation (eg, a template orautorun), Meteor will register adependency on the underlying data. Any change to the collection thatchanges the documents in a cursor will trigger a recomputation. Todisable this behavior, pass {reactive: false} as an option tofind.

Note that when fields are specified, only changes to the includedfields will trigger callbacks in observe, observeChanges andinvalidations in reactive computations using this cursor. Careful useof fields allows for more fine-grained reactivity for computationsthat don’t depend on an entire document.

On the client, there will be a period of time between when the page loads andwhen the published data arrives from the server during which your client-sidecollections will be empty.

Anywhere

Mongo.Collection#findOne([selector], [options])

(mongo/collection.js, line 340)

Finds the first document that matches the selector, as ordered by sort and skip options. Returns undefined if no matching document is found.

Arguments

Options

  • sortMongo Sort Specifier
  • Sort order (default: natural order)

  • skipNumber

  • Number of results to skip at the beginning

  • fieldsMongo Field Specifier

  • Dictionary of fields to return or exclude.

  • reactiveBoolean

  • (Client only) Default true; pass false to disable reactivity

  • transformFunction

  • Overrides transform on the Collection for this cursor. Pass null to disable transformation.

Equivalent to find(selector, options).fetch()[0] withoptions.limit = 1.

Anywhere

Mongo.Collection#insert(doc, [callback])

(mongo/collection.js, line 445)

Insert a document in the collection. Returns its unique _id.

Arguments

  • docObject
  • The document to insert. May not yet have an _id attribute, in which case Meteor will generate one for you.

  • callbackFunction

  • Optional. If present, called with an error object as the first argument and, if no error, the _id as the second.

Add a document to the collection. A document is just an object, andits fields can contain any combination of EJSON-compatible datatypes(arrays, objects, numbers, strings, null, true, and false).

insert will generate a unique ID for the object you pass, insert itin the database, and return the ID. When insert is called fromuntrusted client code, it will be allowed only if passes anyapplicable allow and deny rules.

On the server, if you don’t provide a callback, then insert blocksuntil the database acknowledges the write, or throws an exception ifsomething went wrong. If you do provide a callback, insert stillreturns the ID immediately. Once the insert completes (or fails), thecallback is called with error and result arguments. In an error case,result is undefined. If the insert is successful, error isundefined and result is the new document ID.

On the client, insert never blocks. If you do not provide a callbackand the insert fails on the server, then Meteor will log a warning tothe console. If you provide a callback, Meteor will call that functionwith error and result arguments. In an error case, result isundefined. If the insert is successful, error is undefined andresult is the new document ID.

Example:

  1. const groceriesId = Lists.insert({ name: 'Groceries' });
  2. Items.insert({ list: groceriesId, name: 'Watercress' });
  3. Items.insert({ list: groceriesId, name: 'Persimmons' });

Anywhere

Mongo.Collection#update(selector, modifier, [options], [callback])

(mongo/collection.js, line 531)

Modify one or more documents in the collection. Returns the number of matched documents.

Arguments

  • selectorMongo Selector, Object ID, or String
  • Specifies which documents to modify

  • modifierMongo Modifier

  • Specifies how to modify the documents

  • callbackFunction

  • Optional. If present, called with an error object as the first argument and, if no error, the number of affected documents as the second.

Options

  • multiBoolean
  • True to modify all matching documents; false to only modify one of the matching documents (the default).

  • upsertBoolean

  • True to insert a document if no matching documents are found.

Modify documents that match selector according to modifier (seemodifier documentation).

The behavior of update differs depending on whether it is called bytrusted or untrusted code. Trusted code includes server code andmethod code. Untrusted code includes client-side code such as eventhandlers and a browser’s JavaScript console.

  • Trusted code can modify multiple documents at once by settingmulti to true, and can use an arbitrary Mongoselector to find the documents to modify. It bypassesany access control rules set up by allow anddeny. The number of affected documents will be returnedfrom the update call if you don’t pass a callback.

  • Untrusted code can only modify a single document at once, specifiedby its _id. The modification is allowed only after checking anyapplicable allow and deny rules. The numberof affected documents will be returned to the callback. Untrustedcode cannot perform upserts, except in insecure mode.

On the server, if you don’t provide a callback, then update blocksuntil the database acknowledges the write, or throws an exception ifsomething went wrong. If you do provide a callback, update returnsimmediately. Once the update completes, the callback is called with asingle error argument in the case of failure, or a second argumentindicating the number of affected documents if the update was successful.

On the client, update never blocks. If you do not provide a callbackand the update fails on the server, then Meteor will log a warning tothe console. If you provide a callback, Meteor will call that functionwith an error argument if there was an error, or a second argumentindicating the number of affected documents if the update was successful.

Client example:

  1. // When the 'give points' button in the admin dashboard is pressed, give 5
  2. // points to the current player. The new score will be immediately visible on
  3. // everyone's screens.
  4. Template.adminDashboard.events({
  5. 'click .give-points'() {
  6. Players.update(Session.get('currentPlayer'), {
  7. $inc: { score: 5 }
  8. });
  9. }
  10. });

Server example:

  1. // Give the 'Winner' badge to each user with a score greater than 10. If they
  2. // are logged in and their badge list is visible on the screen, it will update
  3. // automatically as they watch.
  4. Meteor.methods({
  5. declareWinners() {
  6. Players.update({ score: { $gt: 10 } }, {
  7. $addToSet: { badges: 'Winner' }
  8. }, { multi: true });
  9. }
  10. });

You can use update to perform a Mongo upsert by setting the upsertoption to true. You can also use the upsert method to perform anupsert that returns the _id of the document that was inserted (if there was one)in addition to the number of affected documents.

Anywhere

Mongo.Collection#upsert(selector, modifier, [options], [callback])

(mongo/collection.js, line 637)

Modify one or more documents in the collection, or insert one if no matching documents were found. Returns an object with keys numberAffected (the number of documents modified) and insertedId (the unique _id of the document that was inserted, if any).

Arguments

  • selectorMongo Selector, Object ID, or String
  • Specifies which documents to modify

  • modifierMongo Modifier

  • Specifies how to modify the documents

  • callbackFunction

  • Optional. If present, called with an error object as the first argument and, if no error, the number of affected documents as the second.

Options

  • multiBoolean
  • True to modify all matching documents; false to only modify one of the matching documents (the default).

Modify documents that match selector according to modifier, or inserta document if no documents were modified. upsert is the same as callingupdate with the upsert option set to true, except that the returnvalue of upsert is an object that contain the keys numberAffectedand insertedId. (update returns only the number of affected documents.)

Anywhere

Mongo.Collection#remove(selector, [callback])

(mongo/collection.js, line 596)

Remove documents from the collection

Arguments

  • selectorMongo Selector, Object ID, or String
  • Specifies which documents to remove

  • callbackFunction

  • Optional. If present, called with an error object as its argument.

Find all of the documents that match selector and delete them fromthe collection.

The behavior of remove differs depending on whether it is called bytrusted or untrusted code. Trusted code includes server code andmethod code. Untrusted code includes client-side code such as eventhandlers and a browser’s JavaScript console.

  • Trusted code can use an arbitrary Mongo selector tofind the documents to remove, and can remove more than one documentat once by passing a selector that matches multiple documents. Itbypasses any access control rules set up by allow anddeny. The number of removed documents will be returnedfrom remove if you don’t pass a callback.

As a safety measure, if selector is omitted (or is undefined),no documents will be removed. Set selector to {} if you reallywant to remove all documents from your collection.

  • Untrusted code can only remove a single document at a time,specified by its _id. The document is removed only after checkingany applicable allow and deny rules. Thenumber of removed documents will be returned to the callback.

On the server, if you don’t provide a callback, then remove blocksuntil the database acknowledges the write and then returns the numberof removed documents, or throws an exception ifsomething went wrong. If you do provide a callback, remove returnsimmediately. Once the remove completes, the callback is called with asingle error argument in the case of failure, or a second argumentindicating the number of removed documents if the remove was successful.

On the client, remove never blocks. If you do not provide a callbackand the remove fails on the server, then Meteor will log a warning to theconsole. If you provide a callback, Meteor will call that function with anerror argument if there was an error, or a second argument indicating the numberof removed documents if the remove was successful.

Example (client):

  1. // When the 'remove' button is clicked on a chat message, delete that message.
  2. Template.chat.events({
  3. 'click .remove'() {
  4. Messages.remove(this._id);
  5. }
  6. });

Example (server):

  1. // When the server starts, clear the log and delete all players with a karma of
  2. // less than -2.
  3. Meteor.startup(() => {
  4. if (Meteor.isServer) {
  5. Logs.remove({});
  6. Players.remove({ karma: { $lt: -2 } });
  7. }
  8. });

Server

Mongo.Collection#allow(options)

(allow-deny/allow-deny.js, line 45)

Allow users to write directly to this collection from client code, subject to limitations you define.

Options

  • insert, update, removeFunction
  • Functions that look at a proposed modification to the database and return true if it should be allowed.

  • fetchArray of Strings

  • Optional performance enhancement. Limits the fields that will be fetched from the database for inspection by your update and remove functions.

  • transformFunction

  • Overrides transform on the Collection. Pass null to disable transformation.

While allow and deny make it easy to get started building an app, it’sharder than it seems to write secure allow and deny rules. We recommendthat developers avoid allow and deny, and switch directly to custom methodsonce they are ready to remove insecure mode from their app. Seethe Meteor Guide on securityfor more details.

When a client calls insert, update, or remove on a collection, thecollection’s allow and deny callbacks are calledon the server to determine if the write should be allowed. If at leastone allow callback allows the write, and no deny callbacks deny thewrite, then the write is allowed to proceed.

These checks are run only when a client tries to write to the databasedirectly, for example by calling update from inside an eventhandler. Server code is trusted and isn’t subject to allow and denyrestrictions. That includes methods that are called with Meteor.call— they are expected to do their own access checking rather thanrelying on allow and deny.

You can call allow as many times as you like, and each call caninclude any combination of insert, update, and removefunctions. The functions should return true if they think theoperation should be allowed. Otherwise they should return false, ornothing at all (undefined). In that case Meteor will continuesearching through any other allow rules on the collection.

The available callbacks are:

  • insert(userId, doc)
  • The user userId wants to insert the document doc into thecollection. Return true if this should be allowed.

doc will contain the _id field if one was explicitly set by the client, orif there is an active transform. You can use this to prevent users fromspecifying arbitrary _id fields.

  • update(userId, doc, fieldNames, modifier)
  • The user userId wants to update a document doc. (doc is thecurrent version of the document from the database, without theproposed update.) Return true to permit the change.

fieldNames is an array of the (top-level) fields in doc that theclient wants to modify, for example['name', 'score'].

modifier is the raw Mongo modifier thatthe client wants to execute; for example,{ $set: { 'name.first': 'Alice' }, $inc: { score: 1 } }.

Only Mongo modifiers are supported (operations like $set and $push).If the user tries to replace the entire document rather than use$-modifiers, the request will be denied without checking the allowfunctions.

  • remove(userId, doc)
  • The user userId wants to remove doc from the database. Returntrue to permit this.

When calling update or remove Meteor will by default fetch theentire document doc from the database. If you have large documentsyou may wish to fetch only the fields that are actually used by yourfunctions. Accomplish this by setting fetch to an array of fieldnames to retrieve.

Example:

  1. // Create a collection where users can only modify documents that they own.
  2. // Ownership is tracked by an `owner` field on each document. All documents must
  3. // be owned by the user that created them and ownership can't be changed. Only a
  4. // document's owner is allowed to delete it, and the `locked` attribute can be
  5. // set on a document to prevent its accidental deletion.
  6. const Posts = new Mongo.Collection('posts');
  7. Posts.allow({
  8. insert(userId, doc) {
  9. // The user must be logged in and the document must be owned by the user.
  10. return userId && doc.owner === userId;
  11. },
  12. update(userId, doc, fields, modifier) {
  13. // Can only change your own documents.
  14. return doc.owner === userId;
  15. },
  16. remove(userId, doc) {
  17. // Can only remove your own documents.
  18. return doc.owner === userId;
  19. },
  20. fetch: ['owner']
  21. });
  22. Posts.deny({
  23. update(userId, doc, fields, modifier) {
  24. // Can't change owners.
  25. return _.contains(fields, 'owner');
  26. },
  27. remove(userId, doc) {
  28. // Can't remove locked documents.
  29. return doc.locked;
  30. },
  31. fetch: ['locked'] // No need to fetch `owner`
  32. });

If you never set up any allow rules on a collection then all clientwrites to the collection will be denied, and it will only be possible towrite to the collection from server-side code. In this case you willhave to create a method for each possible write that clients are allowedto do. You’ll then call these methods with Meteor.call rather thanhaving the clients call insert, update, and remove directly on thecollection.

Meteor also has a special “insecure mode” for quickly prototyping newapplications. In insecure mode, if you haven’t set up any allow or denyrules on a collection, then all users have full write access to thecollection. This is the only effect of insecure mode. If you call allow ordeny at all on a collection, even Posts.allow({}), then access is checkedjust like normal on that collection. New Meteor projects start in insecuremode by default. To turn it off just run in your terminal:

  1. meteor remove insecure

Server

Mongo.Collection#deny(options)

(allow-deny/allow-deny.js, line 60)

Override allow rules.

Options

  • insert, update, removeFunction
  • Functions that look at a proposed modification to the database and return true if it should be denied, even if an allow rule says otherwise.

  • fetchArray of Strings

  • Optional performance enhancement. Limits the fields that will be fetched from the database for inspection by your update and remove functions.

  • transformFunction

  • Overrides transform on the Collection. Pass null to disable transformation.

While allow and deny make it easy to get started building an app, it’sharder than it seems to write secure allow and deny rules. We recommendthat developers avoid allow and deny, and switch directly to custom methodsonce they are ready to remove insecure mode from their app. Seethe Meteor Guide on securityfor more details.

This works just like allow, except it lets youmake sure that certain writes are definitely denied, even if there is anallow rule that says that they should be permitted.

When a client tries to write to a collection, the Meteor server firstchecks the collection’s deny rules. If none of them return true thenit checks the collection’s allow rules. Meteor allows the write onlyif no deny rules return true and at least one allow rule returnstrue.

Server

Mongo.Collection#rawCollection()

(mongo/collection.js, line 698)

Returns the Collection object corresponding to this collection from the npm mongodb driver module which is wrapped by Mongo.Collection.

The methods (like update or insert) you call on the resulting raw collection return promises and can be used outside of a Fiber.

Server

Mongo.Collection#rawDatabase()

(mongo/collection.js, line 712)

Returns the Db object corresponding to this collection's database connection from the npm mongodb driver module which is wrapped by Mongo.Collection.

Cursors

To create a cursor, use find. To access the documents in acursor, use forEach, map, fetch, or ES2015’s iteration protocols.

Anywhere

Mongo.Cursor#forEach(callback, [thisArg])

(minimongo/cursor.js, line 117)

Call callback once for each matching document, sequentially and synchronously.

Arguments

  • callbackFunction
  • Function to call. It will be called with three arguments: the document, a 0-based index, and cursor itself.

  • thisArgAny

  • An object which will be the value of this inside callback.

This interface is compatible with Array.forEach.

When called from a reactive computation, forEach registers dependencies onthe matching documents.

Examples:

  1. // Print the titles of the five top-scoring posts.
  2. const topPosts = Posts.find({}, { sort: { score: -1 }, limit: 5 });
  3. let count = 0;
  4. topPosts.forEach((post) => {
  5. console.log(`Title of post ${count}: ${post.title}`);
  6. count += 1;
  7. });

Anywhere

Mongo.Cursor#map(callback, [thisArg])

(minimongo/cursor.js, line 156)

Map callback over all matching documents. Returns an Array.

Arguments

  • callbackFunction
  • Function to call. It will be called with three arguments: the document, a 0-based index, and cursor itself.

  • thisArgAny

  • An object which will be the value of this inside callback.

This interface is compatible with Array.map.

When called from a reactive computation, map registers dependencies onthe matching documents.On the server, if callback yields, other calls to callback may occur whilethe first call is waiting. If strict sequential execution is necessary, useforEach instead.

Anywhere

Mongo.Cursor#fetch()

(minimongo/cursor.js, line 65)

Return all matching documents as an Array.

When called from a reactive computation, fetch registers dependencies onthe matching documents.

Anywhere

Mongo.Cursor#count([applySkipLimit])

(minimongo/cursor.js, line 40)

Returns the number of documents that match a query.

Arguments

  • applySkipLimitboolean
  • If set to false, the value returned will reflect the total number of matching documents, ignoring any value supplied for limit

Unlike the other functions, count registers a dependency only on thenumber of matching documents. (Updates that just change or reorder thedocuments in the result set will not trigger a recomputation.)

Anywhere

Mongo.Cursor#observe(callbacks)

(minimongo/cursor.js, line 208)

Watch a query. Receive callbacks as the result set changes.

Arguments

  • callbacksObject
  • Functions to call to deliver the result set as it changes

Establishes a live query that invokes callbacks when the result ofthe query changes. The callbacks receive the entire contents of thedocument that was affected, as well as its old contents, ifapplicable. If you only need to receive the fields that changed, seeobserveChanges.

callbacks may have the following functions as properties:

  • added(document)or
  • addedAt(document, atIndex, before)
  • A new document document entered the result set. The new documentappears at position atIndex. It is immediately before the documentwhose _id is before. before will be null if the new documentis at the end of the results.
  • changed(newDocument, oldDocument) or
  • changedAt(newDocument, oldDocument, atIndex)
  • The contents of a document were previously oldDocument and are nownewDocument. The position of the changed document is atIndex.
  • removed(oldDocument)or
  • removedAt(oldDocument, atIndex)
  • The document oldDocument is no longer in the result set. It used to be at position atIndex.
  • movedTo(document, fromIndex, toIndex, before)
  • A document changed its position in the result set, from fromIndex to toIndex(which is before the document with id before). Its current contents isdocument.

Use added, changed, and removed when you don’t care about theorder of the documents in the result set. They are more efficient thanaddedAt, changedAt, and removedAt.

Before observe returns, added (or addedAt) will be called zeroor more times to deliver the initial results of the query.

observe returns a live query handle, which is an object with a stop method.Call stop with no arguments to stop calling the callback functions and teardown the query. The query will run forever until you call this. Ifobserve is called from a Tracker.autorun computation, it is automaticallystopped when the computation is rerun or stopped.(If the cursor was created with the option reactive set to false, it willonly deliver the initial results and will not call any further callbacks;it is not necessary to call stop on the handle.)

Anywhere

Mongo.Cursor#observeChanges(callbacks)

(minimongo/cursor.js, line 222)

Watch a query. Receive callbacks as the result set changes. Only the differences between the old and new documents are passed to the callbacks.

Arguments

  • callbacksObject
  • Functions to call to deliver the result set as it changes

Establishes a live query that invokes callbacks when the result ofthe query changes. In contrast to observe,observeChanges provides only the difference between the old and newresult set, not the entire contents of the document that changed.

callbacks may have the following functions as properties:

  • added(id, fields)or
  • addedBefore(id, fields, before)
  • A new document entered the result set. It has the id and fieldsspecified. fields contains all fields of the document excluding the_id field. The new document is before the document identified bybefore, or at the end if before is null.
  • changed(id, fields)
  • The document identified by id has changed. fields contains thechanged fields with their new values. If a field was removed from thedocument then it will be present in fields with a value ofundefined.

  • movedBefore(id, before)

  • The document identified by id changed its position in the ordered result set,and now appears before the document identified by before.

  • removed(id)

  • The document identified by id was removed from the result set.

observeChanges is significantly more efficient if you do not useaddedBefore or movedBefore.

Before observeChanges returns, added (or addedBefore) will be calledzero or more times to deliver the initial results of the query.

observeChanges returns a live query handle, which is an object with a stopmethod. Call stop with no arguments to stop calling the callback functionsand tear down the query. The query will run forever until you call this.IfobserveChanges is called from a Tracker.autorun computation, it is automaticallystopped when the computation is rerun or stopped.(If the cursor was created with the option reactive set to false, it willonly deliver the initial results and will not call any further callbacks;it is not necessary to call stop on the handle.)

Unlike observe, observeChanges does not provide absolute positioninformation (that is, atIndex positions rather than beforepositions.) This is for efficiency.

Example:

  1. // Keep track of how many administrators are online.
  2. let count = 0;
  3. const cursor = Users.find({ admin: true, onlineNow: true });
  4. const handle = cursor.observeChanges({
  5. added(id, user) {
  6. count += 1;
  7. console.log(`${user.name} brings the total to ${count} admins.`);
  8. },
  9. removed() {
  10. count -= 1;
  11. console.log(`Lost one. We're now down to ${count} admins.`);
  12. }
  13. });
  14. // After five seconds, stop keeping the count.
  15. setTimeout(() => handle.stop(), 5000);

Anywhere

new Mongo.ObjectID([hexString])

import { Mongo } from 'meteor/mongo' (mongo/collection.js, line 740)

Create a Mongo-style ObjectID. If you don't specify a hexString, the ObjectID will generated randomly (not using MongoDB's ID construction rules).

Arguments

  • hexStringString
  • Optional. The 24-character hexadecimal contents of the ObjectID to create

Mongo.ObjectID follows the same API as the Node MongoDB driverObjectIDclass. Note that you must use the equals method (or EJSON.equals) tocompare them; the === operator will not work. If you are writing generic codethat needs to deal with _id fields that may be either strings or ObjectIDs, useEJSON.equals instead of === to compare them.

ObjectID values created by Meteor will not have meaningful answers to their getTimestamp method, since Meteor currently constructs them fully randomly.

Mongo-Style Selectors

The simplest selectors are just a string orMongo.ObjectID. These selectors match thedocument with that value in its _id field.

A slightly more complex form of selector is an object containing a set of keysthat must match in a document:

  1. // Matches all documents where `deleted` is false.
  2. { deleted: false }
  3. // Matches all documents where the `name` and `cognomen` are as given.
  4. { name: 'Rhialto', cognomen: 'the Marvelous' }
  5. // Matches every document.
  6. {}

But they can also contain more complicated tests:

  1. // Matches documents where `age` is greater than 18.
  2. { age: { $gt: 18 } }
  3. // Matches documents where `tags` is an array containing 'popular'.
  4. { tags: 'popular' }
  5. // Matches documents where `fruit` is one of three possibilities.
  6. { fruit: { $in: ['peach', 'plum', 'pear'] } }

See the completedocumentation.

Mongo-Style Modifiers

A modifier is an object that describes how to update a document inplace by changing some of its fields. Some examples:

  1. // Set the `admin` property on the document to true.
  2. { $set: { admin: true } }
  3. // Add 2 to the `votes` property and add 'Traz' to the end of the `supporters`
  4. // array.
  5. { $inc: { votes: 2 }, $push: { supporters: 'Traz' } }

But if a modifier doesn’t contain any $-operators, then it is insteadinterpreted as a literal document, and completely replaces whatever waspreviously in the database. (Literal document modifiers are not currentlysupported by validated updates.)

  1. // Find the document with ID '123' and completely replace it.
  2. Users.update({ _id: '123' }, { name: 'Alice', friends: ['Bob'] });

See the full list ofmodifiers.

Sort Specifiers

Sorts may be specified using your choice of several syntaxes:

  1. // All of these do the same thing (sort in ascending order by key `a`, breaking
  2. // ties in descending order of key `b`).
  3. [['a', 'asc'], ['b', 'desc']]
  4. ['a', ['b', 'desc']]
  5. { a: 1, b: -1 }
  6. // Sorted by `createdAt` descending.
  7. Users.find({}, { sort: { createdAt: -1 } });
  8. // Sorted by `createdAt` descending and by `name` ascending.
  9. Users.find({}, { sort: [['createdAt', 'desc'], ['name', 'asc']] });

The last form will only work if your JavaScript implementationpreserves the order of keys in objects. Most do, most of the time, butit’s up to you to be sure.

For local collections you can pass a comparator function which receives twodocument objects, and returns -1 if the first document comes first in order,1 if the second document comes first, or 0 if neither document comes beforethe other. This is a Minimongo extension to MongoDB.

Field Specifiers

Queries can specify a particular set of fields to include or exclude from theresult object.

To exclude specific fields from the result objects, the field specifier is adictionary whose keys are field names and whose values are 0. All unspecifiedfields are included.

  1. Users.find({}, { fields: { password: 0, hash: 0 } });

To include only specific fields in the result documents, use 1 asthe value. The _id field is still included in the result.

  1. Users.find({}, { fields: { firstname: 1, lastname: 1 } });

With one exception, it is not possible to mix inclusion and exclusion styles:the keys must either be all 1 or all 0. The exception is that you may specify_id: 0 in an inclusion specifier, which will leave _id out of the resultobject as well. However, such field specifiers can not be used withobserveChanges, observe, cursors returnedfrom a publish function, or cursors used in{{#each}} in a template. They may be used with fetch,findOne, forEach, and map.

Fieldoperators such as $ and $elemMatch are not available on the client sideyet.

A more advanced example:

  1. Users.insert({
  2. alterEgos: [
  3. { name: 'Kira', alliance: 'murderer' },
  4. { name: 'L', alliance: 'police' }
  5. ],
  6. name: 'Yagami Light'
  7. });
  8. Users.findOne({}, { fields: { 'alterEgos.name': 1, _id: 0 } });
  9. // Returns { alterEgos: [{ name: 'Kira' }, { name: 'L' }] }

See the MongoDB docs for details of the nested field rules and array behavior.

Connecting to your database

When developing your application, Meteor starts a local MongoDB instance andautomatically connects to it. In production, you must specify a MONGO_URLenvironment variable pointing at your database in the standard mongo connectionstring format.

You can also set MONGO_URL in development if you want to connect to adifferent MongoDB instance.

If you want to use oplog tailing for livequeries, you should also setMONGO_OPLOG_URL (generally you’ll need a special user with oplog access, butthe detail can differ depending on how you host your MongoDB. Read more here).

As of Meteor 1.4, you must ensure you set the replicaSet parameter on yourMETEOR_OPLOG_URL