documentation - meteor

27
11/10/15 Documentation - Meteor docs.meteor.com/#/basic/underscore 1/27 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

Upload: neil-martino

Post on 20-Feb-2016

77 views

Category:

Documents


1 download

DESCRIPTION

Documentation - Meteor JS

TRANSCRIPT

Page 1: Documentation - Meteor

11/10/15 Documentation - Meteor

docs.meteor.com/#/basic/underscore 1/27

Meteor is an ultra-simple environment for building modern websites. What once took weeks, even withthe 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 applicationserver rendered a screen and sent it over the network to a dumb terminal. Whenever the user did anything, thatserver rerendered a whole new screen. This model served the Web well for over a decade. It gave rise toLAMP, Rails, Django, PHP.

But the best teams, with the biggest budgets and the longest schedules, now build applications in JavaScriptthat run on the client. These apps have stellar interfaces. They don't reload pages. They are reactive: changesfrom 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 canbuild a complete application in a weekend, or a sufficiently caffeinated hackathon. No longer do you need toprovision server resources, or deploy API endpoints in the cloud, or manage a database, or wrangle an ORMlayer, 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_64architectures.

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 theclient render it.

One Language. Meteor lets you write both the client and the server parts of your application inJavaScript.

Database Everywhere. You can use the same methods to access your database from the client or the

Page 2: Documentation - Meteor

11/10/15 Documentation - Meteor

docs.meteor.com/#/basic/underscore 2/27

server.

Latency Compensation. On the client, Meteor prefetches data and simulates models to make it looklike server method calls return instantly.

Full Stack Reactivity. In Meteor, realtime is the default. All layers, from database to template, updatethemselves automatically when necessary.

Embrace the Ecosystem. Meteor is open source and integrates with existing open source tools andframeworks.

Simplicity Equals Productivity. The best way to make something seem simple is to have it actually besimple. 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 hopeyou'll get involved with the project!

TUTORIALGet started fast with the official Meteor tutorial!

STACK OVERFLOWThe best place to ask (and answer!) technical questions is on Stack Overflow. Be sure to add themeteor tag to your question.

FORUMSVisit the Meteor discussion forums to announce projects, get help, talk about the community, ordiscuss changes to core.

GITHUBThe core code is on GitHub. If you're able to write code or file issues, we'd love to have your help. Pleaseread Contributing to Meteor for how to get started.

Command Line Tool

meteor help

Get help on meteor command line usage. Running meteor help by itself will list the common meteorcommands. 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. Seemeteor 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 update was run from an appdirectory) update the packages used by the current app to the latest versions that are compatible with all other

Page 3: Documentation - Meteor

11/10/15 Documentation - Meteor

docs.meteor.com/#/basic/underscore 3/27

packages used by the app.

meteor add

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

meteor remove

Remove a package previously added to your Meteor project. For a list of the packages that your application iscurrently using, use the meteor list command.

meteor mongo

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

meteor reset

Reset the current project to a fresh state. Removes all local data.

If you use meteor reset often, but you have some initial data that you don't want to discard, consider usingMeteor.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, sothere 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.isClient and 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 thespecial 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-relatedJavaScript code.

/server

Any files in this directory are only used on the server, and are never sent to the client. Use /server to storesource files with sensitive logic or data that should not be visible to the client.

/public

Page 4: Documentation - Meteor

11/10/15 Documentation - Meteor

docs.meteor.com/#/basic/underscore 4/27

Files in /public are served to the client as-is. Use this to store assets such as images. For example, if youhave 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 Assets API 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 APIdocumentation.

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 tothe Google Play Store or iOS App Store with just a few commands. We've put a lot of work into making thesame packages and APIs work on desktop and mobile, so that you don't have to worry about a lot of the edgecases associated with mobile app development.

Installing mobile SDKs

Install the development tools for Android or iOS with one command:

meteor install-sdk android # for Android

meteor install-sdk ios # for iOS

Adding platforms

Add the relevant platform to your app:

meteor add-platform android # for Android

meteor add-platform ios # for iOS

Running on a simulator

meteor run android # for Android

meteor run ios # for iOS

Running on a device

meteor run android-device # for Android

meteor run ios-device # for iOS

Configuring app icons and metadata

You can configure your app's icons, title, version number, splash screen, and other metadata with the specialmobile-config.js file.

Learn more about Meteor's mobile support on the GitHub wiki page.

The Meteor API

Page 5: Documentation - Meteor

11/10/15 Documentation - Meteor

docs.meteor.com/#/basic/underscore 5/27

Client

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

Templates

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

Defining Templates in HTML

Templates are defined in .html files that can be located anywhere in your Meteor project folder except theserver, public, and private directories.

Each .html file 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. Templatescan be included more than once — one of the main purposes of templates is to avoid writing the same HTMLmultiple 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 alsodisplay data obtained from helpers. Helpers are written in JavaScript, and can be either simple values orfunctions.

Template.myTemplate.helpers(helpers)

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 name for a template called nametag (in JavaScript):

Page 6: Documentation - Meteor

11/10/15 Documentation - Meteor

docs.meteor.com/#/basic/underscore 6/27

Template.nametag.helpers({

name: "Ben Bitdiddle"

});

And here is the nametag template 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 data and display the HTML inside theblock for each one.{{#if data}} ... {{else}} ... {{/if}} - If data is 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 #each or #with block has its own data context, which is an object whose properties can be usedas helpers inside the block. For #with blocks, 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 datacontext while the block is evaluated for that element.

For instance, if the people helper 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'susername, 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 username helper, the helper function above will be called to determine the user'sname:

<!-- in your HTML -->

<template name="profilePage">

Page 7: Documentation - Meteor

11/10/15 Documentation - Meteor

docs.meteor.com/#/basic/underscore 7/27

Client

<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 availablein 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 Accounts will talk more about how to add dynamicdata to your templates.

Template.myTemplate.events(eventMap)

Specify event handlers for this template.

Arguments

eventMap Event Map

Event handlers to associate with this template.

The event map passed into Template.myTemplate.events has event descriptors as its keys and eventhandler functions as the values. Event handlers get two arguments: the event object and the templateinstance. 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.events as follows:

Template.example.events({

"click .my-button": function (event, template) {

Page 8: Documentation - Meteor

11/10/15 Documentation - Meteor

docs.meteor.com/#/basic/underscore 8/27

Client

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 DOMevent 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 willbe called with the relevant DOM event object and template instance. See the [Event Maps section](#eventmaps) for details.

Template.myTemplate.onRendered

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 isinserted into the page for the first time.

These callbacks can be used to integrate external libraries that aren't familiar with Meteor's automatic viewrendering, and need to be initialized every time HTML is inserted into the page. You can perform initializationor clean-up on any objects in onCreated and onDestroyed callbacks.

For example, to use the HighlightJS library to apply code highlighting to all <pre> elements inside thecodeSample template, you might pass the following function to Template.codeSample.onRendered:

Template.codeSample.onRendered(function () {

hljs.highlightBlock(this.findAll('pre'));

});

In the callback function, this is bound to a template instance object that is unique to this inclusion of thetemplate and remains across re-renderings. You can use methods like this.find and this.findAll toaccess 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 toaccess the HTML elements inside the template and it can be assigned properties that persist as the templateis reactively updated.

Template instance objects can be found in several places:

Page 9: Documentation - Meteor

11/10/15 Documentation - Meteor

docs.meteor.com/#/basic/underscore 9/27

Client

Client

Client

1. The value of this in the created, rendered, and destroyed template callbacks2. The second argument to event handlers3. As Template.instance() inside helpers

You can assign additional properties of your choice to the template instance to keep track of any staterelevant to the template. For example, when using the Google Maps API you could attach the map object tothe current template instance to be able to refer to it in helpers and event handlers. Use the onCreated andonDestroyed callbacks to perform initialization or clean-up.

template.findAll(selector)

Find all elements matching selector in 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)

Find one element matching selector in this template instance.

Arguments

selector String

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

find is just like findAll but only returns the first element found. Like findAll, find only returns elementsfrom 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. Useit to store things like the currently selected item in a list.

What's special about Session is that it's reactive. If you call Session.get("myKey") in a template helper orinside Tracker.autorun, the relevant part of the template will be re-rendered automatically wheneverSession.set("myKey", newValue) is called.

Session.set(key, value)

Set a variable in the session. Notify any listeners that the value has changed (eg: redraw templates, andrerun any Tracker.autorun computations, that called Session.get on this key.)

Arguments

key String

Page 10: Documentation - Meteor

11/10/15 Documentation - Meteor

docs.meteor.com/#/basic/underscore 10/27

Client

The key to set, eg, selectedItem

value EJSON-able Object or undefined

The new value for key

Session.get(key)

Get the value of a session variable. If inside a reactive computation, invalidate the computation the nexttime the value of the variable is changed by Session.set. This returns a clone of the session value, so ifit'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 Session gives us our first taste of reactivity, the idea that the view should update automatically whennecessary, without us having to call a render function manually. In the next section, we will learn how to useTracker, 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 otherfunctions whenever Session variables, database queries, and other data sources change.

Unlike most other systems, you don't have to manually declare these dependencies — it "just works." Themechanism is simple and efficient. Once you've initialized a computation with Tracker.autorun, wheneveryou call a Meteor function that returns data, Tracker automatically records which data were accessed. Later,when this data changes, the computation is rerun automatically. This is how a template knows how to re-render whenever its helper functions have new data to return.

Page 11: Documentation - Meteor

11/10/15 Documentation - Meteor

docs.meteor.com/#/basic/underscore 11/27

ClientTracker.autorun(runFunc, [options])

Run a function now and rerun it later whenever its dependencies change. Returns a Computation objectthat 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 recievesis 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 datasources are updated with new data, the function will be rerun.

For example, you can monitor one Session variable 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 youwant to prevent further rerunning of the function, you can call stop on the computation object that is passed asthe 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.autorun is called, the callback function is invoked immediately, at which point it alertsand stops right away if counter === 2 already. In this example, Session.get("counter") === 0 whenTracker.autorun is called, so nothing happens the first time, and the function is run again each timecounter 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

Page 12: Documentation - Meteor

11/10/15 Documentation - Meteor

docs.meteor.com/#/basic/underscore 12/27

Anywhere

Anywhere

rerun.

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

Collections

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

new Mongo.Collection(name, [options])

Constructor for a Collection

Arguments

name String

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

Calling the Mongo.Collection constructor creates a collection object which acts just like a MongoDBcollection. 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 bestto 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 null as the name, then you're creating a local collection. Local collections are not synchronizedbetween the client and the server; they are just temporary collections of JavaScript objects that supportMongo-style find, insert, update, and remove operations.

By default, Meteor automatically publishes every document in your collection to each connected client. Todisable this behavior, you must remove the autopublish package, in your terminal:

meteor remove autopublish

Then, use Meteor.publish and Meteor.subscribe to specify which parts of your collection should bepublished to which clients.

Use findOne or find to retrieve documents from a collection.

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

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

Arguments

selector Mongo Selector, Object ID, or String

Page 13: Documentation - Meteor

11/10/15 Documentation - Meteor

docs.meteor.com/#/basic/underscore 13/27

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 findOne method is mostcommonly called with a specific document _id:

var post = Posts.findOne(postId);

However, you can also call findOne with a Mongo selector, which is an object that specifies a required set ofattributes 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), andmore in the MongoDB documentation.

One useful behavior that might not be obvious is that Mongo selectors also match items in arrays. Forexample, this selector

Post.findOne({

tags: "meteor"

});

will match this document

{

title: "I love Meteor",

createdBy: "242135223",

tags: ["meteor", "javascript", "fun"]

}

The findOne method is reactive just like Session.get, meaning that, if you use it inside a template helper ora Tracker.autorun callback, it will automatically rerender the view or rerun the computation if the returneddocument changes.

Page 14: Documentation - Meteor

11/10/15 Documentation - Meteor

docs.meteor.com/#/basic/underscore 14/27

Anywhere

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

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

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 find method is similar to findOne, but instead of returning a single document it returns a MongoDBcursor. 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 fetch will rerun when the data changes, the

Page 15: Documentation - Meteor

11/10/15 Documentation - Meteor

docs.meteor.com/#/basic/underscore 15/27

Anywhere

Anywhere

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

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

collection.insert(doc, [callback])

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 foryou.

callback Function

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

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.Collection has an _id field. It must be unique, and is automaticallygenerated if you don't provide one. The _id field can be used to retrieve a specific document usingcollection.findOne.

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

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 ofaffected documents as the second.

Options

multi Boolean

True to modify all matching documents; false to only modify one of the matching documents (thedefault).

Page 16: Documentation - Meteor

11/10/15 Documentation - Meteor

docs.meteor.com/#/basic/underscore 16/27

Anywhere

Server

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. Themodifier is an object that specifies which changes should be made to the matched documents. Watch out -unless you use an operator like $set, update will simply replace the entire matched document with themodifier.

Here's an example of setting the content field 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 update on the client, you can only find documents by their _id field. To useall of the possible selectors, you must call update in server code or from a method.

collection.remove(selector, [callback])

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 find and update, and removes any documents that match theselector from the database. Use remove carefully — 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 canremove documents using any selector.

collection.allow(options)

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 remove from any client orserver code. This is because apps started with meteor create include the insecure package by default tosimplify development. Obviously, if any user could change the database whenever they wanted it would be bad

Page 17: Documentation - Meteor

11/10/15 Documentation - Meteor

docs.meteor.com/#/basic/underscore 17/27

Server

for security, so it is important to remove the insecure package and specify some permissions rules, in yourterminal:

meteor remove insecure

Once you have removed the insecure package, use the allow and deny methods to control who can performwhich operations on the database. By default, all operations on the client are denied, so we need to add someallow 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 remove are called from untrusted client code.

For example, we might say that users can only create new posts if the createdBy field matches the ID of thecurrent 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 allow method accepts three possible callbacks: insert, remove, and update. The first argument to allthree callbacks is the _id of the logged in user, and the remaining arguments are as follows:

1. insert(userId, document)

document is the document that is about to be inserted into the database. Return true if the insert shouldbe allowed, false otherwise.

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

document is the document that is about to be modified. fieldNames is an array of top-level fields that areaffected by this change. modifier is the Mongo Modifier that was passed as the second argument ofcollection.update. It can be difficult to achieve correct validation using this callback, so it isrecommended to use methods instead. Return true if the update should be allowed, false otherwise.

3. remove(userId, document)

document is the document that is about to be removed from the database. Return true if the documentshould be removed, false otherwise.

collection.deny(options)

Override allow rules.

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.

Page 18: Documentation - Meteor

11/10/15 Documentation - Meteor

docs.meteor.com/#/basic/underscore 18/27

Client

Anywhere but publish functions

Anywhere but publish functions

Anywhere

The deny method lets you selectively override your allow rules. While only one of your allow callbacks has toreturn true to allow a modification, every one of your deny callbacks has to return false for the databasechange to happen.

For example, if we wanted to override part of our allow rule 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 anautomatically generated UI that will let users log into your app. There are several communityalternatives to this package that change the appearance, or you can not use it and use the advancedAccounts methods instead.accounts-password: This package will allow users to log in with passwords. When you add it theloginButtons dropdown will automatically gain email and password fields.accounts-facebook, accounts-google, accounts-github, accounts-twitter, and communitypackages for other services will allow your users to log in with their accounts from other websites.These will automatically add buttons to the loginButtons dropdown.

{{> loginButtons}}

Include the loginButtons template somewhere in your HTML to use Meteor's default UI for logging in. To usethis, you need to add the accounts-ui package, in your terminal:

meteor add accounts-ui

Meteor.user()

Get the current user record, or null if no user is logged in. A reactive data source.

Get the logged in user from the Meteor.users collection. Equivalent toMeteor.users.findOne(Meteor.userId()).

Meteor.userId()

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

Meteor.users

Page 19: Documentation - Meteor

11/10/15 Documentation - Meteor

docs.meteor.com/#/basic/underscore 19/27

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: "[email protected]", verified: true },

{ address: "[email protected]", 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 fieldsspecially:

username: a unique String identifying the user.emails: an Array of Objects with keys address and verified; an email address may belong to atmost one user. verified is a Boolean which is true if the user has verified the address with a tokensent 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 fieldcontains tokens used by forgot password links, and its resume field contains tokens used to keep youlogged in between sessions.

Like all Mongo.Collections, you can access all documents on the server, but only those specifically publishedby the server are available on the client.

By default, the current user's username, emails and profile are published to the client. You can publishadditional 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();

Page 20: Documentation - Meteor

11/10/15 Documentation - Meteor

docs.meteor.com/#/basic/underscore 20/27

Anywhere

}});

// 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 services that are meant to be public (egservices.facebook.id, services.twitter.screenName). Additionally, when using autopublish moreinformation is published for the currently logged in user, including access tokens. This allows making API callsdirectly from the client for services that allow this.

Users are by default allowed to specify their own profile field with Accounts.createUser and modify it withMeteor.users.update. To allow users to edit additional fields, use Meteor.users.allow. To forbid users frommaking 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 todo something more complicated than insert, update or remove, or when you need to do data validation thatis difficult to achieve with just allow and deny.

Methods can return values and throw errors.

Meteor.methods(methods)

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.methods on the server defines functions that can be called remotely by clients. Here's anexample 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.");

Page 21: Documentation - Meteor

11/10/15 Documentation - Meteor

docs.meteor.com/#/basic/underscore 21/27

Anywhere

}

// ... do stuff ...

return "something";

},

otherMethod: function () {

// ... do other stuff ...

}

});

The check function is a convenient way to enforce the expected types and structure of method arguments.

Inside your method definition, this is bound to a method invocation object, which has several usefulproperties, including this.userId, which identifies the currently logged-in user.

You don't have to put all your method definitions into a single Meteor.methods call; you may call it multipletimes, 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 hadto wait a whole second to see their comment show up due to this delay. That's why Meteor has a featurecalled method stubs. If you define a method on the client with the same name as a server method, Meteor willrun 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 tomake client-side interactions with the database appear instant.

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

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 resultof the call. The callback will be called with two arguments, error and result. The error argument will benull unless an exception was thrown. When an exception is thrown, the error argument is a Meteor.Errorinstance and the result argument is undefined.

Page 22: Documentation - Meteor

11/10/15 Documentation - Meteor

docs.meteor.com/#/basic/underscore 22/27

Anywhere

Here's an example of calling the commentOnPost method with arguments comment and 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-sidecallback 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 iscomplete, 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])

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 methodto 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 check throw errors with a number in thisfield.

reason String

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

details String

Page 23: Documentation - Meteor

11/10/15 Documentation - Meteor

docs.meteor.com/#/basic/underscore 23/27

Server

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, butMeteor.Error is the only kind of error that will be sent to the client. If a method function throws a differentexception, 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 thosepublications with Meteor.subscribe. Any documents the client subscribes to will be available through thefind method of client collections.

By default, every newly created Meteor app contains the autopublish package, which automaticallypublishes all available documents to every client. To exercise finer-grained control over what documentsdifferent clients receive, first remove autopublish, in your terminal:

meteor remove autopublish

Now you can use Meteor.publish and Meteor.subscribe to control what documents flow from the server toits clients.

Meteor.publish(name, func)

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 allconnected clients.

func Function

Function called on the server each time a client subscribes. Inside the function, this is the publishhandler object, described below. If the client passed arguments to subscribe, the function is calledwith the same arguments.

To publish data to clients, call Meteor.publish on 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 collection with aquery 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.find results:

// Publish a single post and its comments

Meteor.publish("postAndComments", function (postId) {

// Check argument

check(postId, String);

Page 24: Documentation - Meteor

11/10/15 Documentation - Meteor

docs.meteor.com/#/basic/underscore 24/27

Client

return [

Posts.find({ _id: postId }),

Comments.find({ postId: roomId })

];

});

Inside the publish function, this.userId is the current logged-in user's _id, which can be useful for filteringcollections so that certain documents are visible only to certain users. If the logged-in user changes for aparticular client, the publish function will be automatically rerun with the new userId, so the new user will nothave access to any documents that were meant only for the previous user.

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

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 onStop and onReady callbacks. If there is an error, it is passed as an argumentto onStop. If a function is passed instead of an object, it is interpreted as an onReady callback.

Clients call Meteor.subscribe to express interest in document collections published by the server. Clientscan further filter these collections of documents by calling collection.find(query). Whenever any data thatwas accessed by a publish function changes on the server, the publish function is automatically rerun and theupdated document collections are pushed to the subscribed client.

The onReady callback is called with no arguments when the server has sent all of the initial data for thesubscription. The onStop callback is when the subscription is terminated for any reason; it receives aMeteor.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 thesubscription'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.subscribe inside Tracker.autorun, the subscription will be cancelled automaticallywhenever the computation reruns (so that a new subscription can be created, if appropriate), meaning youdon't have to to call stop on subscriptions made from inside Tracker.autorun.

Environment

Page 25: Documentation - Meteor

11/10/15 Documentation - Meteor

docs.meteor.com/#/basic/underscore 25/27

Anywhere

Anywhere

Anywhere

Meteor.isClient

Boolean variable. True if running in client environment.

Meteor.isServer

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 passwordsor authentication mechanisms, should be kept in the server directory.

Meteor.startup(func)

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 theclient, 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 executedbefore the environment is ready.

For example, to create some initial data if the database is empty when the server starts up, you might use thefollowing pattern:

if (Meteor.isServer) {

Meteor.startup(function () {

if (Rooms.find().count() === 0) {

Rooms.insert({name: "Initial room"});

}

});

}

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

Packages

All of Meteor's functionality is implemented in modular packages. In addition to the core packagesdocumented 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 add and meteor remove:

# add the less package

Page 26: Documentation - Meteor

11/10/15 Documentation - Meteor

docs.meteor.com/#/basic/underscore 26/27

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 dependenciesare tracked in .meteor/packages, so your collaborators will be automatically updated to the same set ofinstalled packages as you after they pull your source code, because they have the same .meteor/packagesfile as you.

You can see which packages are used by your app by running meteor list in 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 packagesdirectly using the meteor search command.

Packages that have a : in the name, such as mquandalle:jade, are written and maintained by communitymembers. 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 themost useful packages.

accounts-ui

This is a drop-in user interface to Meteor's accounts system. After adding the package, include it in yourtemplates with {{> loginButtons}}. The UI automatically adapts to include controls for any added loginservices, 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 .coffee extension will be compiled toJavaScript 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 .jade extension willbe 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 thatworks across most browsers.

JQuery is automatically included in every Meteor app since the framework uses it extensively. See the JQuery

Page 27: Documentation - Meteor

11/10/15 Documentation - Meteor

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

docs for more details.

http

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

less

Add the LESS CSS preprocessor to your app to compile any files with a .less extension into standard CSS.If you want to use @import to 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. underscoreis 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 yourapp'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 morespecific explanations, check out the Full API Docs.