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.
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
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.
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.
# 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
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.
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
Object
docs.meteor.com/#/basic/underscore
5/27
11/10/15
Documentation - Meteor
Template.nametag.helpers({
name: "Ben Bitdiddle"
});
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
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"}]
});
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
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
Event Map
7/27
11/10/15
Documentation - Meteor
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
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
template.findAll(selector)
Client
String
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
String
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
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
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.
Anywhere
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
docs.meteor.com/#/basic/underscore
12/27
11/10/15
Documentation - Meteor
Number
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/}
});
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"
});
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
Number
Number
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
collection.insert(doc, [callback])
Anywhere
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."
});
Anywhere
Modify one or more documents in the collection. Returns the number of affected documents.
Arguments
selector
Mongo Modifier
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
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
Function
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
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()
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()
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 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
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
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.
Anywhere
String
EJSON-able Object
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
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);
Anywhere
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
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').
Now you can use Meteor.publishand Meteor.subscribeto control what documents flow from the server to
its clients.
Meteor.publish(name, func)
Server
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.
Client
String
Any
Function or Object
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
Meteor.isServer
Anywhere
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
Function
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
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.
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
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.
docs.meteor.com/#/basic/underscore
27/27
Molto più che documenti.
Scopri tutto ciò che Scribd ha da offrire, inclusi libri e audiolibri dei maggiori editori.
Annulla in qualsiasi momento.