- Collections
- new Mongo.Collection(name, [options])
- Mongo.Collection#find([selector], [options])
- Mongo.Collection#findOne([selector], [options])
- Mongo.Collection#insert(doc, [callback])
- Mongo.Collection#update(selector, modifier, [options], [callback])
- Mongo.Collection#upsert(selector, modifier, [options], [callback])
- Mongo.Collection#remove(selector, [callback])
- Mongo.Collection#allow(options)
- Mongo.Collection#deny(options)
- Mongo.Collection#rawCollection()
- Mongo.Collection#rawDatabase()
- Cursors
- new Mongo.ObjectID([hexString])
- Mongo-Style Selectors
- Mongo-Style Modifiers
- Sort Specifiers
- Field Specifiers
- Connecting to your database
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. Passnull
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'
: randomMongo.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
orfindOne
, and before being passed to callbacks ofobserve
,map
,forEach
,allow
, anddeny
. Transforms are not applied for the callbacks ofobserveChanges
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. Defaulttrue
.
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 _id
property whose value is unique in the collection, which Meteor will set when youfirst create the document.
// Common code on client and server declares a DDP-managed Mongo collection.
const Chatrooms = new Mongo.Collection('chatrooms');
const Messages = new Mongo.Collection('messages');
The function returns an object with methods to insert
documents 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).
// Return an array of my messages.
const myMessages = Messages.find({ userId: Meteor.userId() }).fetch();
// Create a new message.
Messages.insert({ text: 'Hello, world!' });
// Mark my first message as important.
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 specified
connection
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:
meteor remove autopublish
and instead call Meteor.publish
to specify which parts ofyour collection should be published to which users.
// Create a collection called `Posts` and put a document in it. The document
// will be immediately visible in the local copy of the collection. It will be
// written to the server-side database a fraction of a second later, and a
// fraction of a second after that, it will be synchronized down to any other
// clients that are subscribed to a query that includes it (see
// `Meteor.subscribe` and `autopublish`).
const Posts = new Mongo.Collection('posts');
Posts.insert({ title: 'Hello world', body: 'First post' });
// Changes are visible immediately—no waiting for a round trip to the server.
assert(Posts.find().count() === 1);
// Create a temporary, local collection. It works just like any other collection
// but it doesn't send changes to the server, and it can't receive any data from
// subscriptions.
const Scratchpad = new Mongo.Collection;
for (let i = 0; i < 10; i += 1) {
Scratchpad.insert({ number: i * 2 });
}
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).
// An animal class that takes a document in its constructor.
class Animal {
constructor(doc) {
_.extend(this, doc);
}
makeNoise() {
console.log(this.sound);
}
}
// Define a collection that uses `Animal` as its document.
const Animals = new Mongo.Collection('animals', {
transform: (doc) => new Animal(doc)
});
// Create an animal and call its `makeNoise` method.
Animals.insert({ name: 'raptor', sound: 'roar' });
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 transform
time.
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
- selectorMongo Selector, Object ID, or String
- A query describing the documents to find
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
; passfalse
to disable reactivitytransformFunction
Overrides
transform
on theCollection
for this cursor. Passnull
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
- selectorMongo Selector, Object ID, or String
- A query describing the documents to find
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 theCollection
for this cursor. Passnull
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:
const groceriesId = Lists.insert({ name: 'Groceries' });
Items.insert({ list: groceriesId, name: 'Watercress' });
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 setting
multi
to true, and can use an arbitrary Mongoselector to find the documents to modify. It bypassesany access control rules set up byallow
anddeny
. The number of affected documents will be returnedfrom theupdate
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 anyapplicableallow
anddeny
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:
// When the 'give points' button in the admin dashboard is pressed, give 5
// points to the current player. The new score will be immediately visible on
// everyone's screens.
Template.adminDashboard.events({
'click .give-points'() {
Players.update(Session.get('currentPlayer'), {
$inc: { score: 5 }
});
}
});
Server example:
// Give the 'Winner' badge to each user with a score greater than 10. If they
// are logged in and their badge list is visible on the screen, it will update
// automatically as they watch.
Meteor.methods({
declareWinners() {
Players.update({ score: { $gt: 10 } }, {
$addToSet: { badges: 'Winner' }
}, { multi: true });
}
});
You can use update
to perform a Mongo upsert by setting the upsert
option 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 numberAffected
and 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 returnedfromremove
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 applicableallow
anddeny
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):
// When the 'remove' button is clicked on a chat message, delete that message.
Template.chat.events({
'click .remove'() {
Messages.remove(this._id);
}
});
Example (server):
// When the server starts, clear the log and delete all players with a karma of
// less than -2.
Meteor.startup(() => {
if (Meteor.isServer) {
Logs.remove({});
Players.remove({ karma: { $lt: -2 } });
}
});
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
andremove
functions.transformFunction
- Overrides
transform
on theCollection
. Passnull
to disable transformation.
While
allow
anddeny
make it easy to get started building an app, it’sharder than it seems to write secureallow
anddeny
rules. We recommendthat developers avoidallow
anddeny
, and switch directly to custom methodsonce they are ready to removeinsecure
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 deny
restrictions. 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 remove
functions. 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 documentdoc
into thecollection. Returntrue
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 documentdoc
. (doc
is thecurrent version of the document from the database, without theproposed update.) Returntrue
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 allow
functions.
- remove(userId, doc)
- The user
userId
wants to removedoc
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:
// Create a collection where users can only modify documents that they own.
// Ownership is tracked by an `owner` field on each document. All documents must
// be owned by the user that created them and ownership can't be changed. Only a
// document's owner is allowed to delete it, and the `locked` attribute can be
// set on a document to prevent its accidental deletion.
const Posts = new Mongo.Collection('posts');
Posts.allow({
insert(userId, doc) {
// The user must be logged in and the document must be owned by the user.
return userId && doc.owner === userId;
},
update(userId, doc, fields, modifier) {
// Can only change your own documents.
return doc.owner === userId;
},
remove(userId, doc) {
// Can only remove your own documents.
return doc.owner === userId;
},
fetch: ['owner']
});
Posts.deny({
update(userId, doc, fields, modifier) {
// Can't change owners.
return _.contains(fields, 'owner');
},
remove(userId, doc) {
// Can't remove locked documents.
return doc.locked;
},
fetch: ['locked'] // No need to fetch `owner`
});
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 deny
rules 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:
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
andremove
functions.transformFunction
- Overrides
transform
on theCollection
. Passnull
to disable transformation.
While
allow
anddeny
make it easy to get started building an app, it’sharder than it seems to write secureallow
anddeny
rules. We recommendthat developers avoidallow
anddeny
, and switch directly to custom methodsonce they are ready to removeinsecure
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
insidecallback
.
This interface is compatible with Array.forEach.
When called from a reactive computation, forEach
registers dependencies onthe matching documents.
Examples:
// Print the titles of the five top-scoring posts.
const topPosts = Posts.find({}, { sort: { score: -1 }, limit: 5 });
let count = 0;
topPosts.forEach((post) => {
console.log(`Title of post ${count}: ${post.title}`);
count += 1;
});
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
insidecallback
.
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 positionatIndex
. It is immediately before the documentwhose_id
isbefore
.before
will benull
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 isatIndex
. - removed(oldDocument)or
- removedAt(oldDocument, atIndex)
- The document
oldDocument
is no longer in the result set. It used to be at positionatIndex
. - movedTo(document, fromIndex, toIndex, before)
- A document changed its position in the result set, from
fromIndex
totoIndex
(which is before the document with idbefore
). 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
andfields
specified.fields
contains all fields of the document excluding the_id
field. The new document is before the document identified bybefore
, or at the end ifbefore
isnull
. - 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 infields
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 bybefore
.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 stop
method. 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 thanbefore
positions.) This is for efficiency.
Example:
// Keep track of how many administrators are online.
let count = 0;
const cursor = Users.find({ admin: true, onlineNow: true });
const handle = cursor.observeChanges({
added(id, user) {
count += 1;
console.log(`${user.name} brings the total to ${count} admins.`);
},
removed() {
count -= 1;
console.log(`Lost one. We're now down to ${count} admins.`);
}
});
// After five seconds, stop keeping the count.
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 driverObjectID
class. 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 ObjectID
s, useEJSON.equals
instead of ===
to compare them.
ObjectID
values created by Meteor will not have meaningful answers to theirgetTimestamp
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:
// Matches all documents where `deleted` is false.
{ deleted: false }
// Matches all documents where the `name` and `cognomen` are as given.
{ name: 'Rhialto', cognomen: 'the Marvelous' }
// Matches every document.
{}
But they can also contain more complicated tests:
// Matches documents where `age` is greater than 18.
{ age: { $gt: 18 } }
// Matches documents where `tags` is an array containing 'popular'.
{ tags: 'popular' }
// Matches documents where `fruit` is one of three possibilities.
{ 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:
// Set the `admin` property on the document to true.
{ $set: { admin: true } }
// Add 2 to the `votes` property and add 'Traz' to the end of the `supporters`
// array.
{ $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.)
// Find the document with ID '123' and completely replace it.
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:
// All of these do the same thing (sort in ascending order by key `a`, breaking
// ties in descending order of key `b`).
[['a', 'asc'], ['b', 'desc']]
['a', ['b', 'desc']]
{ a: 1, b: -1 }
// Sorted by `createdAt` descending.
Users.find({}, { sort: { createdAt: -1 } });
// Sorted by `createdAt` descending and by `name` ascending.
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.
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.
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:
Users.insert({
alterEgos: [
{ name: 'Kira', alliance: 'murderer' },
{ name: 'L', alliance: 'police' }
],
name: 'Yagami Light'
});
Users.findOne({}, { fields: { 'alterEgos.name': 1, _id: 0 } });
// 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_URL
environment 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