Вы находитесь на странице: 1из 27

11/10/15

Documentation - Meteor

Meteor is an ultra-simple environment for building modern websites. What once took weeks, even with
the best tools, now takes hours with Meteor.
The web was originally designed to work in the same way that mainframes worked in the 70s. The application
server rendered a screen and sent it over the network to a dumb terminal. Whenever the user did anything, that
server rerendered a whole new screen. This model served the Web well for over a decade. It gave rise to
LAMP, Rails, Django, PHP.
But the best teams, with the biggest budgets and the longest schedules, now build applications in JavaScript
that run on the client. These apps have stellar interfaces. They don't reload pages. They are reactive: changes
from any client immediately appear on everyone's screen.
They've built them the hard way. Meteor makes it an order of magnitude simpler, and a lot more fun. You can
build a complete application in a weekend, or a sufficiently caffeinated hackathon. No longer do you need to
provision server resources, or deploy API endpoints in the cloud, or manage a database, or wrangle an ORM
layer, or swap back and forth between JavaScript and Ruby, or broadcast data invalidations to clients.

Quick start!
Meteor supports OS X, Windows, and Linux.
On Windows? Download the official Meteor installer here.
On OS X or Linux? Install the latest official Meteor release from your terminal:
$ curl https://install.meteor.com/ | sh

The Windows installer supports Windows 7, Windows 8.1, Windows Server 2008, and Windows Server 2012.
The command line installer supports Mac OS X 10.7 (Lion) and above, and Linux on x86 and x86_64
architectures.
Once you've installed Meteor, create a project:
meteor create myapp

Run it locally:
cd myapp
meteor
# Meteor server running on: http://localhost:3000/

Then, open a new terminal tab and unleash it on the world (on a free server we provide):
meteor deploy myapp.meteor.com

Principles of Meteor
Data on the Wire. Meteor doesn't send HTML over the network. The server sends data and lets the
client render it.
One Language. Meteor lets you write both the client and the server parts of your application in
JavaScript.
Database Everywhere. You can use the same methods to access your database from the client or the
docs.meteor.com/#/basic/underscore

1/27

11/10/15

Documentation - Meteor

server.
Latency Compensation. On the client, Meteor prefetches data and simulates models to make it look
like server method calls return instantly.
Full Stack Reactivity. In Meteor, realtime is the default. All layers, from database to template, update
themselves automatically when necessary.
Embrace the Ecosystem. Meteor is open source and integrates with existing open source tools and
frameworks.
Simplicity Equals Productivity. The best way to make something seem simple is to have it actually be
simple. Meteor's main functionality has clean, classically beautiful APIs.

Learning Resources
There are many community resources for getting help with your app. If Meteor catches your interest, we hope
you'll get involved with the project!
TUTORIAL
Get started fast with the official Meteor tutorial!
STACK OVERFLOW
The best place to ask (and answer!) technical questions is on Stack Overflow. Be sure to add the
meteor tag to your question.
FORUMS
Visit the Meteor discussion forums to announce projects, get help, talk about the community, or
discuss changes to core.
GITHUB
The core code is on GitHub. If you're able to write code or file issues, we'd love to have your help. Please
read Contributing to Meteor for how to get started.

Command Line Tool


meteor help
Get help on meteorcommand line usage. Running meteor helpby itself will list the common meteor
commands. Running meteor help <command>will print detailed help about meteor <command>.
meteor create <name>

Make a subdirectory called <name>and create a new Meteor app there.


meteor run

Serve the current app at http://localhost:3000 using Meteor's local development server.
meteor debug

Run the project with Node Inspector attached, so that you can step through your server code line by line. See
meteor debug in the full docs for more information.
meteor deploy <site>

Bundle your app and deploy it to <site>. Meteor provides free hosting if you deploy to
<your app>.meteor.com as long as <your app> is a name that has not been claimed by someone else.
meteor update

Update your Meteor installation to the latest released version and then (if meteor updatewas run from an app
directory) update the packages used by the current app to the latest versions that are compatible with all other
docs.meteor.com/#/basic/underscore

2/27

11/10/15

Documentation - Meteor

packages used by the app.


meteor add

Add a package (or multiple packages) to your Meteor project. To query for available packages, use the
meteor search command.
meteor remove

Remove a package previously added to your Meteor project. For a list of the packages that your application is
currently using, use the meteor listcommand.
meteor mongo

Opens a MongoDB shell for viewing and/or manipulating collections stored in the database. Note that you
must already be running a server for the current app (in another terminal window) in order for meteor mongoto
connect to the app's database.
meteor reset

Reset the current project to a fresh state. Removes all local data.
If you use meteor resetoften, but you have some initial data that you don't want to discard, consider using
Meteor.startup to recreate that data the first time the server starts up:
if (Meteor.isServer) {
Meteor.startup(function () {
if (Rooms.find().count() === 0) {
Rooms.insert({name: "Initial room"});
}
});
}

File Structure
Meteor is very flexible about how you structure the files in your app. It automatically loads all of your files, so
there is no need to use <script>or <link>tags to include JavaScript or CSS.

Default file loading


If files are outside of the special directories listed below, Meteor does the following:
1. HTML templates are compiled and sent to the client. See the templates section for more details.
2. CSS files are sent to the client. In production mode they are automatically concatenated and minified.
3. JavaScript is loaded on the client and the server. You can use Meteor.isClientand Meteor.isServer
to control where certain blocks of code run.
If you want more control over which JavaScript code is loaded on the client and the server, you can use the
special directories listed below.

Special directories
/client

Any files here are only served to the client. This is a good place to keep your HTML, CSS, and UI-related
JavaScript code.
/server

Any files in this directory are only used on the server, and are never sent to the client. Use /serverto store
source files with sensitive logic or data that should not be visible to the client.
/public
docs.meteor.com/#/basic/underscore

3/27

11/10/15

Documentation - Meteor

Files in /publicare served to the client as-is. Use this to store assets such as images. For example, if you
have an image located at /public/background.png, you can include it in your HTML with
<img src='/background.png'/> or in your CSS with background-image:
url(/background.png). Note that /public is not part of the image URL.
/private

These files can only be accessed by server code through AssetsAPI and are not accessible to the client.
Read more about file load order and special directories in the Structuring Your App section of the full API
documentation.

Building Mobile Apps


Once you've built your web app with Meteor, you can easily build a native wrapper for your app and publish it to
the Google Play Store or iOS App Store with just a few commands. We've put a lot of work into making the
same packages and APIs work on desktop and mobile, so that you don't have to worry about a lot of the edge
cases associated with mobile app development.

Installing mobile SDKs


Install the development tools for Android or iOS with one command:
meteor install-sdk android
meteor install-sdk ios

# for Android
# for iOS

Adding platforms
Add the relevant platform to your app:
meteor add-platform android
meteor add-platform ios

# for Android
# for iOS

Running on a simulator
meteor run android
meteor run ios

# for Android
# for iOS

Running on a device
meteor run android-device
meteor run ios-device

# for Android
# for iOS

Configuring app icons and metadata


You can configure your app's icons, title, version number, splash screen, and other metadata with the special
mobile-config.js file.
Learn more about Meteor's mobile support on the GitHub wiki page.

The Meteor API


docs.meteor.com/#/basic/underscore

4/27

11/10/15

Documentation - Meteor

Your JavaScript code can run in two environments: the client (browser), and the server (a Node.js container on
a server). For each function in this API reference, we'll indicate if the function is available just on the client, just
on the server, or Anywhere.

Templates
In Meteor, views are defined in templates. A template is a snippet of HTML that can include dynamic data. You
can also interact with your templates from JavaScript code to insert data and listen to events.

Defining Templates in HTML


Templates are defined in .htmlfiles that can be located anywhere in your Meteor project folder except the
server, public, and private directories.
Each .htmlfile can contain any number of the following top-level elements: <head>, <body>, or <template>.
Code in the <head>and <body>tags is appended to that section of the HTML page, and code inside
<template> tags can be included using {{> templateName}}, as shown in the example below. Templates
can be included more than once one of the main purposes of templates is to avoid writing the same HTML
multiple times by hand.
<!-- add code to the <head> of the page -->
<head>
<title>My website!</title>
</head>
<!-- add code to the <body> of the page -->
<body>
<h1>Hello!</h1>
{{> welcomePage}}
</body>
<!-- define a template called welcomePage -->
<template name="welcomePage">
<p>Welcome to my website!</p>
</template>

The {{ ... }}syntax is part of a language called Spacebars that Meteor uses to add functionality to HTML.
As shown above, it lets you include templates in other parts of your page. Using Spacebars, you can also
display data obtained from helpers. Helpers are written in JavaScript, and can be either simple values or
functions.

Template.myTemplate.helpers(helpers)

Client

Specify template helpers available to this template.


Arguments
helpers

Object

Dictionary of helper functions by name.


Here's how you might define a helper called namefor a template called nametag(in JavaScript):

docs.meteor.com/#/basic/underscore

5/27

11/10/15

Documentation - Meteor

Template.nametag.helpers({
name: "Ben Bitdiddle"
});

And here is the nametagtemplate itself (in HTML):


<!-- In an HTML file, display the value of the helper -->
<template name="nametag">
<p>My name is {{name}}.</p>
</template>

Spacebars also has a few other handy control structures that can be used to make your views more dynamic:
{{#each data}} ... {{/each}} -

Iterate over the items in dataand display the HTML inside the

block for each one.


{{#if data}} ... {{else}} ... {{/if}} -

If datais true, display the first block; if it is false,

display the second one.


{{#with data}} ... {{/with}} -

Set the data context of the HTML inside, and display it.

Each nested #eachor #withblock has its own data context, which is an object whose properties can be used
as helpers inside the block. For #withblocks, the data context is simply the value that appears after the
#with and before the }} characters. For #each blocks, each element of the given array becomes the data
context while the block is evaluated for that element.
For instance, if the peoplehelper has the following value
Template.welcomePage.helpers({
people: [{name: "Bob"}, {name: "Frank"}, {name: "Alice"}]
});

then you can display every person's name as a list of <p>tags:


{{#each people}}
<p>{{name}}</p>
{{/each}}

or use the "nametag" template from above instead of <p>tags:


{{#each people}}
{{> nametag}}
{{/each}}

Remember that helpers can be functions as well as simple values. For example, to show the logged in user's
username, you might define a function-valued helper called username:
// in your JS file
Template.profilePage.helpers({
username: function () {
return Meteor.user() && Meteor.user().username;
}
});

Now, each time you use the usernamehelper, the helper function above will be called to determine the user's
name:
<!-- in your HTML -->
<template name="profilePage">
docs.meteor.com/#/basic/underscore

6/27

11/10/15

Documentation - Meteor

<p>Profile page for {{username}}</p>


</template>

Helpers can also take arguments. For example, here's a helper that pluralizes a word:
Template.post.helpers({
commentCount: function (numComments) {
if (numComments === 1) {
return "1 comment";
} else {
return numComments + " comments";
}
}
});

Pass in arguments by putting them inside the curly braces after the name of the helper:
<p>There are {{commentCount 3}}.</p>

The helpers above have all been associated with specific templates, but you can also make a helper available
in all templates by using Template.registerHelper.
You can find detailed documentation for Spacebars in the README on GitHub. Later in this documentation,
the sections about Session, Tracker, Collections, and Accountswill talk more about how to add dynamic
data to your templates.

Template.myTemplate.events(eventMap)

Client

Specify event handlers for this template.


Arguments
eventMap

Event Map

Event handlers to associate with this template.


The event map passed into Template.myTemplate.eventshas event descriptors as its keys and event
handler functions as the values. Event handlers get two arguments: the event object and the template
instance. Event handlers can also access the data context of the target element in this.
To attach event handlers to the following template
<template name="example">
{{#with myHelper}}
<button class="my-button">My button</button>
<form>
<input type="text" name="myInput" />
<input type="submit" value="Submit Form" />
</form>
{{/with}}
</template>

you might call Template.example.eventsas follows:


Template.example.events({
"click .my-button": function (event, template) {
docs.meteor.com/#/basic/underscore

7/27

11/10/15

Documentation - Meteor

alert("My button was clicked!");


},
"submit form": function (event, template) {
var inputValue = event.target.myInput.value;
var helperValue = this;
alert(inputValue, helperValue);
}
});

The first part of the key (before the first space) is the name of the event being captured. Pretty much any DOM
event is supported. Some common ones are: click, mousedown, mouseup, mouseenter, mouseleave,
keydown, keyup, keypress, focus, blur, and change.
The second part of the key (after the first space) is a CSS selector that indicates which elements to listen to.
This can be almost any selector supported by JQuery.
Whenever the indicated event happens on the selected element, the corresponding event handler function will
be called with the relevant DOM event object and template instance. See the [Event Maps section]
(#eventmaps) for details.

Template.myTemplate.onRendered

Client

Register a function to be called when an instance of this template is inserted into the DOM.
Arguments
callback

Function

A function to be added as a callback.


The functions added with this method are called once for every instance of Template.myTemplate when it is
inserted into the page for the first time.
These callbacks can be used to integrate external libraries that aren't familiar with Meteor's automatic view
rendering, and need to be initialized every time HTML is inserted into the page. You can perform initialization
or clean-up on any objects in onCreatedand onDestroyedcallbacks.
For example, to use the HighlightJS library to apply code highlighting to all <pre>elements inside the
codeSample template, you might pass the following function to Template.codeSample.onRendered:
Template.codeSample.onRendered(function () {
hljs.highlightBlock(this.findAll('pre'));
});

In the callback function, thisis bound to a template instance object that is unique to this inclusion of the
template and remains across re-renderings. You can use methods like this.findand this.findAllto
access DOM nodes in the template's rendered HTML.

Template instances
A template instance object represents a single inclusion of a template in the document. It can be used to
access the HTML elements inside the template and it can be assigned properties that persist as the template
is reactively updated.
Template instance objects can be found in several places:
docs.meteor.com/#/basic/underscore

8/27

11/10/15

Documentation - Meteor

1. The value of thisin the created, rendered, and destroyedtemplate callbacks


2. The second argument to event handlers
3. As Template.instance()inside helpers
You can assign additional properties of your choice to the template instance to keep track of any state
relevant to the template. For example, when using the Google Maps API you could attach the mapobject to
the current template instance to be able to refer to it in helpers and event handlers. Use the onCreatedand
onDestroyed callbacks to perform initialization or clean-up.

template.findAll(selector)

Client

Find all elements matching selectorin this template instance.


Arguments
selector

String

The CSS selector to match, scoped to the template contents.


template.findAll returns

an array of DOM elements matching selector. You can also use template.$,
which works exactly like the JQuery $function but only returns elements within template.

template.find(selector)

Client

Find one element matching selectorin this template instance.


Arguments
selector

String

The CSS selector to match, scoped to the template contents.


find is

just like findAllbut only returns the first element found. Like findAll, findonly returns elements
from inside the template.

Session
Session provides

a global object on the client that you can use to store an arbitrary set of key-value pairs. Use
it to store things like the currently selected item in a list.
What's special about Sessionis that it's reactive. If you call Session.get("myKey")in a template helper or
inside Tracker.autorun, the relevant part of the template will be re-rendered automatically whenever
Session.set("myKey", newValue) is called.

Session.set(key, value)

Client

Set a variable in the session. Notify any listeners that the value has changed (eg: redraw templates, and
rerun any Tracker.autoruncomputations, that called Session.geton this key.)
Arguments
key

String

docs.meteor.com/#/basic/underscore

9/27

11/10/15

Documentation - Meteor

The key to set, eg, selectedItem


value

EJSON-able Object or undefined

The new value for key

Session.get(key)

Client

Get the value of a session variable. If inside a reactive computation, invalidate the computation the next
time the value of the variable is changed by Session.set. This returns a clone of the session value, so if
it's an object or an array, mutating the returned value has no effect on the value stored in the session.
Arguments
key

String

The name of the session variable to return


Example:
<!-- In your template -->
<template name="main">
<p>We've always been at war with {{theEnemy}}.</p>
</template>
// In your JavaScript
Template.main.helpers({
theEnemy: function () {
return Session.get("enemy");
}
});
Session.set("enemy", "Eastasia");
// Page will say "We've always been at war with Eastasia"
Session.set("enemy", "Eurasia");
// Page will change to say "We've always been at war with Eurasia"

Using Sessiongives us our first taste of reactivity, the idea that the view should update automatically when
necessary, without us having to call a renderfunction manually. In the next section, we will learn how to use
Tracker, the lightweight library that makes this possible in Meteor.

Tracker
Meteor has a simple dependency tracking system which allows it to automatically rerun templates and other
functions whenever Sessionvariables, database queries, and other data sources change.
Unlike most other systems, you don't have to manually declare these dependencies it "just works." The
mechanism is simple and efficient. Once you've initialized a computation with Tracker.autorun, whenever
you call a Meteor function that returns data, Trackerautomatically records which data were accessed. Later,
when this data changes, the computation is rerun automatically. This is how a template knows how to rerender whenever its helper functions have new data to return.

docs.meteor.com/#/basic/underscore

10/27

11/10/15

Documentation - Meteor

Tracker.autorun(runFunc, [options])

Client

Run a function now and rerun it later whenever its dependencies change. Returns a Computation object
that can be used to stop or observe the rerunning.
Arguments
runFunc

Function

The function to run. It receives one argument: the Computation object that will be returned.
Options
onError

Function

Optional. The function to run when an error happens in the Computation. The only argument it recieves
is the Error thrown. Defaults to the error being logged to the console.
Tracker.autorun allows

you to run a function that depends on reactive data sources. Whenever those data
sources are updated with new data, the function will be rerun.
For example, you can monitor one Sessionvariable and set another:
Tracker.autorun(function () {
var celsius = Session.get("celsius");
Session.set("fahrenheit", celsius * 9/5 + 32);
});

Or you can wait for a session variable to have a certain value, and do something the first time it does. If you
want to prevent further rerunning of the function, you can call stopon the computation object that is passed as
the first parameter to the callback function:
// Initialize a session variable called "counter" to 0
Session.set("counter", 0);
// The autorun function runs but does not alert (counter: 0)
Tracker.autorun(function (computation) {
if (Session.get("counter") === 2) {
computation.stop();
alert("counter reached two");
}
});
// The autorun function runs but does not alert (counter: 1)
Session.set("counter", Session.get("counter") + 1);
// The autorun function runs and alerts "counter reached two"
Session.set("counter", Session.get("counter") + 1);
// The autorun function no longer runs (counter: 3)
Session.set("counter", Session.get("counter") + 1);

The first time Tracker.autorunis called, the callback function is invoked immediately, at which point it alerts
and stops right away if counter === 2already. In this example, Session.get("counter") === 0when
Tracker.autorun is called, so nothing happens the first time, and the function is run again each time
counter changes, until computation.stop() is called after counter reaches 2.
If the initial run of an autorun throws an exception, the computation is automatically stopped and won't be
docs.meteor.com/#/basic/underscore

11/27

11/10/15

Documentation - Meteor

rerun.
To learn more about how Trackerworks and to explore advanced ways to use it, visit the Tracker chapter in
the Meteor Manual, which describes it in much more detail.

Collections
Meteor stores data in collections. JavaScript objects stored in collections are called documents. To get
started, declare a collection with new Mongo.Collection.

new Mongo.Collection(name, [options])

Anywhere

Constructor for a Collection


Arguments
name

String

The name of the collection. If null, creates an unmanaged (unsynchronized) local collection.
Calling the Mongo.Collectionconstructor creates a collection object which acts just like a MongoDB
collection. If you pass a name when you create the collection, then you are declaring a persistent collection
one that is stored on the server and can be published to clients.
To allow both client code and server code to access the same collection using the same API, it's usually best
to declare collections as global variables in a JavaScript file that's present on both client and server.
Here's an example of declaring two named, persistent collections as global variables:
// In a JS file that's loaded on the client and the server
Posts = new Mongo.Collection("posts");
Comments = new Mongo.Collection("comments");

If you pass nullas the name, then you're creating a local collection. Local collections are not synchronized
between the client and the server; they are just temporary collections of JavaScript objects that support
Mongo-style find, insert, update, and removeoperations.
By default, Meteor automatically publishes every document in your collection to each connected client. To
disable this behavior, you must remove the autopublishpackage, in your terminal:
meteor remove autopublish

Then, use Meteor.publishand Meteor.subscribeto specify which parts of your collection should be
published to which clients.
Use findOneor findto retrieve documents from a collection.

collection.findOne([selector], [options])

Anywhere

Finds the first document that matches the selector, as ordered by sort and skip options.
Arguments
selector

Mongo Selector, Object ID, or String

docs.meteor.com/#/basic/underscore

12/27

11/10/15

Documentation - Meteor

A query describing the documents to find


Options
sort

Mongo Sort Specifier

Sort order (default: natural order)


skip

Number

Number of results to skip at the beginning


fields

Mongo Field Specifier

Dictionary of fields to return or exclude.


This method lets you retrieve a specific document from your collection. The findOnemethod is most
commonly called with a specific document _id:
var post = Posts.findOne(postId);

However, you can also call findOnewith a Mongo selector, which is an object that specifies a required set of
attributes of the desired document. For example, this selector
var post = Posts.findOne({
createdBy: "12345",
title: {$regex: /first/}
});

will match this document


{
createdBy: "12345",
title: "My first post!",
content: "Today was a good day."
}

You can read about MongoDB query operators such as $regex, $lt(less than), $text(text search), and
more in the MongoDB documentation.
One useful behavior that might not be obvious is that Mongo selectors also match items in arrays. For
example, this selector
Post.findOne({
tags: "meteor"
});

will match this document


{
title: "I love Meteor",
createdBy: "242135223",
tags: ["meteor", "javascript", "fun"]
}

The findOnemethod is reactive just like Session.get, meaning that, if you use it inside a template helper or
a Tracker.autoruncallback, it will automatically rerender the view or rerun the computation if the returned
document changes.
docs.meteor.com/#/basic/underscore

13/27

11/10/15

Documentation - Meteor

Note that findOnewill return nullif it fails to find a matching document, which often happens if the document
hasn't been loaded yet or has been removed from the collection, so you should be prepared to handle null
values.

collection.find([selector], [options])

Anywhere

Find the documents in a collection that match the selector.


Arguments
selector

Mongo Selector, Object ID, or String

A query describing the documents to find


Options
sort

Mongo Sort Specifier

Sort order (default: natural order)


skip

Number

Number of results to skip at the beginning


limit

Number

Maximum number of results to return


fields

Mongo Field Specifier

Dictionary of fields to return or exclude.


The findmethod is similar to findOne, but instead of returning a single document it returns a MongoDB
cursor. A cursor is a special object that represents a list of documents that might be returned from a query.
You can pass a cursor into a template helper anywhere you could pass an array:
Template.blog.helpers({
posts: function () {
// this helper returns a cursor of
// all of the posts in the collection
return Posts.find();
}
});
<!-- a template that renders multiple posts -->
<template name="blog">
{{#each posts}}
<h1>{{title}}</h1>
<p>{{content}}</p>
{{/each}}
</template>

When you want to retrieve the current list of documents from a cursor, call the cursor's .fetch()method:
// get an array of posts
var postsArray = Posts.find().fetch();

Keep in mind that while the computation in which you call fetchwill rerun when the data changes, the
docs.meteor.com/#/basic/underscore

14/27

11/10/15

Documentation - Meteor

resulting array will not be reactive if it is passed somewhere else.


You can modify the data stored in a Mongo.Collectionby calling insert, update, or remove.

collection.insert(doc, [callback])

Anywhere

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


Arguments
doc

Object

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

Function

Optional. If present, called with an error object as the first argument and, if no error, the _id as the
second.
Here's how you insert a document into a collection:
Posts.insert({
createdBy: Meteor.userId(),
createdAt: new Date(),
title: "My first post!",
content: "Today was a good day."
});

Every document in every Mongo.Collectionhas an _idfield. It must be unique, and is automatically


generated if you don't provide one. The _idfield can be used to retrieve a specific document using
collection.findOne.

collection.update(selector, modifier, [options], [callback])

Anywhere

Modify one or more documents in the collection. Returns the number of affected documents.
Arguments
selector

Mongo Selector, Object ID, or String

Specifies which documents to modify


modifier

Mongo Modifier

Specifies how to modify the documents


callback

Function

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
multi

Boolean

True to modify all matching documents; false to only modify one of the matching documents (the
default).
docs.meteor.com/#/basic/underscore

15/27

11/10/15

Documentation - Meteor

upsert

Boolean

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


The selector here is just like the one you would pass to find, and can match multiple documents. The
modifier is an object that specifies which changes should be made to the matched documents. Watch out unless you use an operator like $set, updatewill simply replace the entire matched document with the
modifier.
Here's an example of setting the contentfield on all posts whose titles contain the word "first":
Posts.update({
title: {$regex: /first/}
}, {
$set: {content: "Tomorrow will be a great day."}
});

You can read about all of the different operators that are supported in the MongoDB documentation.
There's one catch: when you call updateon the client, you can only find documents by their _idfield. To use
all of the possible selectors, you must call updatein server code or from a method.

collection.remove(selector, [callback])

Anywhere

Remove documents from the collection


Arguments
selector

Mongo Selector, Object ID, or String

Specifies which documents to remove


callback

Function

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


This method uses the same selectors as findand update, and removes any documents that match the
selector from the database. Use removecarefully there's no way to get that data back.
As with update, client code can only remove documents by _id, whereas server code and methods can
remove documents using any selector.

collection.allow(options)

Server

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

Function

Functions that look at a proposed modification to the database and return true if it should be allowed.
In newly created apps, Meteor allows almost any calls to insert, update, and removefrom any client or
server code. This is because apps started with meteor createinclude the insecurepackage by default to
simplify development. Obviously, if any user could change the database whenever they wanted it would be bad
docs.meteor.com/#/basic/underscore

16/27

11/10/15

Documentation - Meteor

for security, so it is important to remove the insecurepackage and specify some permissions rules, in your
terminal:
meteor remove insecure

Once you have removed the insecurepackage, use the allowand denymethods to control who can perform
which operations on the database. By default, all operations on the client are denied, so we need to add some
allow rules. Keep in mind that server code and code inside methods are not affected by allow and deny
these rules only apply when insert, update, and removeare called from untrusted client code.
For example, we might say that users can only create new posts if the createdByfield matches the ID of the
current user, so that users can't impersonate each other.
// In a file loaded on the server (ignored on the client)
Posts.allow({
insert: function (userId, post) {
// can only create posts where you are the author
return post.createdBy === userId;
},
remove: function (userId, post) {
// can only delete your own posts
return post.createdBy === userId;
}
// since there is no update field, all updates
// are automatically denied
});

The allowmethod accepts three possible callbacks: insert, remove, and update. The first argument to all
three callbacks is the _idof the logged in user, and the remaining arguments are as follows:
1. insert(userId, document)
document is the document that
be allowed, falseotherwise.

is about to be inserted into the database. Return trueif the insert should

2. update(userId, document, fieldNames, modifier)


document is

the document that is about to be modified. fieldNamesis an array of top-level fields that are
affected by this change. modifieris the Mongo Modifier that was passed as the second argument of
collection.update. It can be difficult to achieve correct validation using this callback, so it is
recommended to use methods instead. Return trueif the update should be allowed, falseotherwise.
3. remove(userId, document)
document is

the document that is about to be removed from the database. Return trueif the document
should be removed, falseotherwise.

collection.deny(options)

Server

Override allowrules.
Options
insert, update, remove

Function

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.
docs.meteor.com/#/basic/underscore

17/27

11/10/15

Documentation - Meteor

The denymethod lets you selectively override your allowrules. While only one of your allowcallbacks has to
return true to allow a modification, every one of your denycallbacks has to return false for the database
change to happen.
For example, if we wanted to override part of our allowrule above to exclude certain post titles:
// In a file loaded on the server (ignored on the client)
Posts.deny({
insert: function (userId, post) {
// Don't allow posts with a certain title
return post.title === "First!";
}
});

Accounts
To get accounts functionality, add one or more of the following packages to your app with meteor add:
accounts-ui:

This package allows you to use {{> loginButtons}}in your templates to add an
automatically generated UI that will let users log into your app. There are several community
alternatives to this package that change the appearance, or you can not use it and use the advanced
Accounts methods instead.
accounts-password: This package will allow users to log in with passwords. When you add it the
loginButtons dropdown will automatically gain email and password fields.
accounts-facebook, accounts-google, accounts-github, accounts-twitter, and community
packages for other services will allow your users to log in with their accounts from other websites.
These will automatically add buttons to the loginButtonsdropdown.

{{> loginButtons}}

Client

Include the loginButtonstemplate somewhere in your HTML to use Meteor's default UI for logging in. To use
this, you need to add the accounts-uipackage, in your terminal:
meteor add accounts-ui

Meteor.user()

Anywhere but publish functions

Get the current user record, or nullif no user is logged in. A reactive data source.
Get the logged in user from the Meteor.userscollection. Equivalent to
Meteor.users.findOne(Meteor.userId()).

Meteor.userId()

Anywhere but publish functions

Get the current user id, or nullif no user is logged in. A reactive data source.

Meteor.users
docs.meteor.com/#/basic/underscore

Anywhere
18/27

11/10/15

Documentation - Meteor

A Mongo.Collection containing user documents.


This collection contains one document per registered user. Here's an example user document:
{
_id: "bbca5d6a-2156-41c4-89da-0329e8c99a4f", // Meteor.userId()
username: "cool_kid_13", // unique name
emails: [
// each email address can only belong to one user.
{ address: "cool@example.com", verified: true },
{ address: "another@different.com", verified: false }
],
createdAt: Wed Aug 21 2013 15:16:52 GMT-0700 (PDT),
profile: {
// The profile is writable by the user by default.
name: "Joe Schmoe"
},
services: {
facebook: {
id: "709050", // facebook id
accessToken: "AAACCgdX7G2...AbV9AZDZD"
},
resume: {
loginTokens: [
{ token: "97e8c205-c7e4-47c9-9bea-8e2ccc0694cd",
when: 1349761684048 }
]
}
}
}

A user document can contain any data you want to store about a user. Meteor treats the following fields
specially:
username: a unique String identifying the user.
emails: an Array of Objects with keys address and verified; an email address may belong to at
most one user. verifiedis a Boolean which is true if the user has verified the address with a token

sent over email.


createdAt: the Date at which the user document was created.
profile: an Object which (by default) the user can create and update with any data.
services: an Object containing data used by particular login services. For example, its reset field
contains tokens used by forgot password links, and its resumefield contains tokens used to keep you
logged in between sessions.
Like all Mongo.Collections, you can access all documents on the server, but only those specifically published
by the server are available on the client.
By default, the current user's username, emailsand profileare published to the client. You can publish
additional fields for the current user with:
// server
Meteor.publish("userData", function () {
if (this.userId) {
return Meteor.users.find({_id: this.userId},
{fields: {'other': 1, 'things': 1}});
} else {
this.ready();
docs.meteor.com/#/basic/underscore

19/27

11/10/15

Documentation - Meteor

}
});
// client
Meteor.subscribe("userData");

If the autopublish package is installed, information about all users on the system is published to all clients.
This includes username, profile, and any fields in servicesthat are meant to be public (eg
services.facebook.id, services.twitter.screenName). Additionally, when using autopublish more
information is published for the currently logged in user, including access tokens. This allows making API calls
directly from the client for services that allow this.
Users are by default allowed to specify their own profilefield with Accounts.createUserand modify it with
Meteor.users.update. To allow users to edit additional fields, use Meteor.users.allow. To forbid users from
making any modifications to their user document:
Meteor.users.deny({update: function () { return true; }});

{{ currentUser }}
Calls Meteor.user(). Use {{#if currentUser}}to check whether the user is logged in.

Methods
Methods are server functions that can be called from the client. They are useful in situations where you want to
do something more complicated than insert, updateor remove, or when you need to do data validation that
is difficult to achieve with just allowand deny.
Methods can return values and throw errors.

Meteor.methods(methods)

Anywhere

Defines functions that can be invoked over the network by clients.


Arguments
methods

Object

Dictionary whose keys are method names and values are functions.
Calling Meteor.methodson the server defines functions that can be called remotely by clients. Here's an
example of a method that checks its arguments and throws an error:
// On the server
Meteor.methods({
commentOnPost: function (comment, postId) {
// Check argument types
check(comment, String);
check(postId, String);
if (! this.userId) {
throw new Meteor.Error("not-logged-in",
"Must be logged in to post a comment.");
docs.meteor.com/#/basic/underscore

20/27

11/10/15

Documentation - Meteor

}
// ... do stuff ...
return "something";
},
otherMethod: function () {
// ... do other stuff ...
}
});

The checkfunction is a convenient way to enforce the expected types and structure of method arguments.
Inside your method definition, thisis bound to a method invocation object, which has several useful
properties, including this.userId, which identifies the currently logged-in user.
You don't have to put all your method definitions into a single Meteor.methodscall; you may call it multiple
times, as long as each method has a unique name.

Latency Compensation
Calling a method on the server requires a round-trip over the network. It would be really frustrating if users had
to wait a whole second to see their comment show up due to this delay. That's why Meteor has a feature
called method stubs. If you define a method on the client with the same name as a server method, Meteor will
run it to attempt to predict the outcome of the server method. When the code on the server actually finishes,
the prediction generated on the client will be replaced with the actual outcome of the server method.
The client versions of insert, update, and remove, which are implemented as methods, use this feature to
make client-side interactions with the database appear instant.

Meteor.call(name, [arg1, arg2...], [asyncCallback])

Anywhere

Invokes a method passing any number of arguments.


Arguments
name

String

Name of method to invoke


arg1, arg2...

EJSON-able Object

Optional method arguments


asyncCallback

Function

Optional callback, which is called asynchronously with the error or result after the method is complete.
If not provided, the method runs synchronously if possible (see below).
This is how you call a method.

On the client
Methods called on the client run asynchronously, so you need to pass a callback in order to observe the result
of the call. The callback will be called with two arguments, errorand result. The errorargument will be
null unless an exception was thrown. When an exception is thrown, the error argument is a Meteor.Error
instance and the resultargument is undefined.
docs.meteor.com/#/basic/underscore

21/27

11/10/15

Documentation - Meteor

Here's an example of calling the commentOnPostmethod with arguments commentand postId:


// Asynchronous call with a callback on the client
Meteor.call('commentOnPost', comment, postId, function (error, result) {
if (error) {
// handle error
} else {
// examine result
}
});

Meteor tracks the database updates performed as part of a method call, and waits to invoke the client-side
callback until all of those updates have been sent to the client.

On the server
On the server, you don't have to pass a callback the method call will simply block until the method is
complete, returning a result or throwing an exception, just as if you called the function directly:
// Synchronous call on the server with no callback
var result = Meteor.call('commentOnPost', comment, postId);

new Meteor.Error(error, [reason], [details])

Anywhere

This class represents a symbolic error thrown by a method.


Arguments
error

String

A string code uniquely identifying this kind of error. This string should be used by callers of the method
to determine the appropriate action to take, instead of attempting to parse the reason or details fields.
For example:
// on the server, pick a code unique to this error
// the reason field should be a useful debug message
throw new Meteor.Error("logged-out",
"The user must be logged in to post a comment.");
// on the client
Meteor.call("methodName", function (error) {
// identify the error
if (error && error.error === "logged-out") {
// show a nice error message
Session.set("errorMessage", "Please log in to post a comment.");
}
});

For legacy reasons, some built-in Meteor functions such as checkthrow errors with a number in this
field.
reason

String

Optional. A short human-readable summary of the error, like 'Not Found'.


details

String

docs.meteor.com/#/basic/underscore

22/27

11/10/15

Documentation - Meteor

Optional. Additional information about the error, like a textual stack trace.
If you want to return an error from a method, throw an exception. Methods can throw any kind of exception, but
Meteor.Error is the only kind of error that will be sent to the client. If a method function throws a different
exception, the client gets Meteor.Error(500, 'Internal server error').

Publish and subscribe


Meteor servers can publish sets of documents with Meteor.publish, and clients can subscribe to those
publications with Meteor.subscribe. Any documents the client subscribes to will be available through the
find method of client collections.
By default, every newly created Meteor app contains the autopublishpackage, which automatically
publishes all available documents to every client. To exercise finer-grained control over what documents
different clients receive, first remove autopublish, in your terminal:
meteor remove autopublish

Now you can use Meteor.publishand Meteor.subscribeto control what documents flow from the server to
its clients.

Meteor.publish(name, func)

Server

Publish a record set.


Arguments
name

String

Name of the record set. If null, the set has no name, and the record set is automatically sent to all
connected clients.
func

Function

Function called on the server each time a client subscribes. Inside the function, thisis the publish
handler object, described below. If the client passed arguments to subscribe, the function is called
with the same arguments.
To publish data to clients, call Meteor.publishon the server with two arguments: the name of the record set,
and a publish function that will be called each time a client subscribes to this record set.
Publish functions typically return the result of calling collection.find(query)on some collectionwith a
query that narrows down the set of documents to publish from that collection:
// Publish the logged in user's posts
Meteor.publish("posts", function () {
return Posts.find({ createdBy: this.userId });
});

You can publish documents from multiple collections by returning an array of collection.findresults:
// Publish a single post and its comments
Meteor.publish("postAndComments", function (postId) {
// Check argument
check(postId, String);
docs.meteor.com/#/basic/underscore

23/27

11/10/15

Documentation - Meteor

return [
Posts.find({ _id: postId }),
Comments.find({ postId: roomId })
];
});

Inside the publish function, this.userIdis the current logged-in user's _id, which can be useful for filtering
collections so that certain documents are visible only to certain users. If the logged-in user changes for a
particular client, the publish function will be automatically rerun with the new userId, so the new user will not
have access to any documents that were meant only for the previous user.

Meteor.subscribe(name, [arg1, arg2...], [callbacks])

Client

Subscribe to a record set. Returns a handle that provides stop()and ready()methods.


Arguments
name

String

Name of the subscription. Matches the name of the server's publish()call.


arg1, arg2...

Any

Optional arguments passed to publisher function on server.


callbacks

Function or Object

Optional. May include onStopand onReadycallbacks. If there is an error, it is passed as an argument


to onStop. If a function is passed instead of an object, it is interpreted as an onReadycallback.
Clients call Meteor.subscribeto express interest in document collections published by the server. Clients
can further filter these collections of documents by calling collection.find(query). Whenever any data that
was accessed by a publish function changes on the server, the publish function is automatically rerun and the
updated document collections are pushed to the subscribed client.
The onReadycallback is called with no arguments when the server has sent all of the initial data for the
subscription. The onStopcallback is when the subscription is terminated for any reason; it receives a
Meteor.Error if the subscription failed due to a server-side error.
Meteor.subscribe returns

a subscription handle, which is an object with the following methods:

stop()
Cancel the subscription. This will typically result in the server directing the client to remove the
subscription's data from the client's cache.

ready()
Returns true if the server has marked the subscription as ready. A reactive data source.
If you call Meteor.subscribeinside Tracker.autorun, the subscription will be cancelled automatically
whenever the computation reruns (so that a new subscription can be created, if appropriate), meaning you
don't have to to call stopon subscriptions made from inside Tracker.autorun.

Environment
docs.meteor.com/#/basic/underscore

24/27

11/10/15

Documentation - Meteor

Meteor.isClient

Anywhere

Boolean variable. True if running in client environment.

Meteor.isServer

Anywhere

Boolean variable. True if running in server environment.

Meteor.isServer can

be used to limit where code runs, but it does not prevent code from being sent to
the client. Any sensitive code that you don't want served to the client, such as code containing passwords
or authentication mechanisms, should be k ept in the serverdirectory.

Meteor.startup(func)

Anywhere

Run code when a client or a server starts.


Arguments
func

Function

A function to run on startup.


On the server, the callback function will run as soon as the server process is finished starting up. On the
client, the callback function will run as soon as the page is ready.
It's good practice to wrap all code that isn't inside template events, template helpers, Meteor.methods,
Meteor.publish, or Meteor.subscribe in Meteor.startup so that your application code isn't executed
before the environment is ready.
For example, to create some initial data if the database is empty when the server starts up, you might use the
following pattern:
if (Meteor.isServer) {
Meteor.startup(function () {
if (Rooms.find().count() === 0) {
Rooms.insert({name: "Initial room"});
}
});
}

If you call Meteor.startupon the server after the server process has started up, or on the client after the page
is ready, the callback will fire immediately.

Packages
All of Meteor's functionality is implemented in modular packages. In addition to the core packages
documented above, there are many others that you can add to your app to enable useful functionality.
From the command line, you can add and remove packages with meteor addand meteor remove:
# add the less package
docs.meteor.com/#/basic/underscore

25/27

11/10/15

Documentation - Meteor

meteor add less


# remove the less package
meteor remove less

Your app will restart itself automatically when you add or remove a package. An app's package dependencies
are tracked in .meteor/packages, so your collaborators will be automatically updated to the same set of
installed packages as you after they pull your source code, because they have the same .meteor/packages
file as you.
You can see which packages are used by your app by running meteor listin the app's directory.

Searching for packages


Currently the best way to search for packages available from the official Meteor package server is Atmosphere,
the community package search website maintained by Percolate Studio. You can also search for packages
directly using the meteor searchcommand.
Packages that have a :in the name, such as mquandalle:jade, are written and maintained by community
members. The prefix before the colon is the name of the user or organization who created that package.
Unprefixed packages are maintained by Meteor Development Group as part of the Meteor framework.
There are currently over 2000 packages available on Atmosphere. Below is a small selection of some of the
most useful packages.

accounts-ui
This is a drop-in user interface to Meteor's accounts system. After adding the package, include it in your
templates with {{> loginButtons}}. The UI automatically adapts to include controls for any added login
services, such as accounts-password, accounts-facebook, etc.
See the docs about accounts-ui above..

coffeescript
Use CoffeeScript in your app. With this package, any files with a .coffeeextension will be compiled to
JavaScript by Meteor's build system.

email
Send emails from your app. See the email section of the full API docs.

mquandalle:jade
Use the Jade templating language in your app. After adding this package, any files with a .jadeextension will
be compiled into Meteor templates. See the page on Atmosphere for details.

jquery
JQuery makes HTML traversal and manipulation, event handling, and animation easy with a simple API that
works across most browsers.
JQuery is automatically included in every Meteor app since the framework uses it extensively. See the JQuery
docs.meteor.com/#/basic/underscore

26/27

11/10/15

Documentation - Meteor

docs for more details.

http
This package allows you to make HTTP requests from the client or server using the same API. See the http
docs to see how to use it.

less
Add the LESS CSS preprocessor to your app to compile any files with a .lessextension into standard CSS.
If you want to use @importto include other files and not have Meteor automatically compile them, use the
.import.less extension.

markdown
Include Markdown code in your templates. It's as easy as using the {{#
markdown}} helper:
<div class="my-div">
{{#markdown}}
# My heading
Some paragraph text
{{/markdown}}
</div>

Just make sure to keep your markdown unindented, since whitespace matters.

underscore
Underscore provides a collection of useful functions to manipulate arrays, objects, and functions. underscore
is included in every Meteor app because the framework itself uses it extensively.

spiderable
This package gives your app server-side rendering to allow search engine crawlers and other bots see your
app's contents. If you care about SEO, you should add this package.

Check out the Full API Docs


Congratulations, you're at the end of the Meteor basic documentation. For more advanced features and more
specific explanations, check out the Full API Docs.

docs.meteor.com/#/basic/underscore

27/27