Quick start!

クイックスタート!

Meteor supports OS X, Windows, and Linux.

MeteorはOS X、Windows、Linuxをサポートしています。

On Windows? Download the official Meteor installer here.

Windows用のMeteorインストーラはここからダウンロードできます。

On OS X or Linux? Install the latest official Meteor release from your terminal:

OS XまたはLinuxならMeteor最新版をターミナルからインストールできます。

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

WindowsインストーラはWindows 7、Windows 8.1、Windows Server 2008、Windows Server 2012をサポートしています。コマンドインストーラはMac OS X 10.7 (Lion)以上、またx86とx86_64アーキテクチャ上のLinuxをサポートしています。

Once you've installed Meteor, create a project:

Meteorをインストールしたら、プロジェクトを作成しましょう。

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が提供している無料のサーバ上で起動します):

meteor deploy myapp.meteor.com

Developer Resources

Tutorial
チュートリアル
Get started fast with the official Meteor tutorial!
Meteor公式チュートリアル

Guide
Learn about best practices in the Meteor Guide!

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.
技術的な質問と回答に最適な場所はStack Overflowです。質問の際はMeteorタグを追加してください。

Forums
フォーラム
Visit the Meteor discussion forumsto 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.
コアコードはGithub上にあります。あなたの貢献をお待ちしています。貢献の際は、Contributing to Meteorをお読みください。

Concepts

コンセプト

Structuring your application

アプリケーションを構造化する

A Meteor application is a mix of client-side JavaScript that runs inside a web browser or PhoneGap mobile app, server-side JavaScript that runs on the Meteor server inside a Node.js container, and all the supporting HTML templates, CSS rules, and static assets. Meteor automates the packaging and transmission of these different components, and it is quite flexible about how you choose to structure those components in your file tree.

Meteorのアプリケーションの構成要素はウェブブラウザやモバイルアプリで動くクライアント・サイドJavaScriptと、Node.jsコンテナ内のMeteorサーバーで動くサーバーサイドJavaScript、そしてHTMLテンプレート、CSS、静的アセットなどからできています。Meteorはこれらの様々なコンポーネントを自動的にパッケージング、送信を行っています。そしてそれらのコンポーネントを含むファイル・ツリー内で、どう構造化するかは非常に自由度が高いものになっています。

Special Directories

特別なディレクトリ

By default, any JavaScript files in your Meteor folder are bundled and sent to the client and the server. However, the names of the files and directories inside your project can affect their load order, where they are loaded, and some other characteristics. Here is a list of file and directory names that are treated specially by Meteor:

初期状態では、Meteorフォルダー内にあるJavaScriptファイルはひと固まりであり、クライアントとサーバー双方に送られています。しかしながら、ファイルやディレクトリの名前によって、ファイルのロードのされ方を変えることができます。あるファイルはクライアント側にロードされ、他のはサーバー固有のファイルにできます。Meteorにおいて特別に扱われるファイル名とディレクトリ名は、以下のリストにあるものです。

  • client

    Any directory named client is not loaded on the server. Similar to wrapping your code in if (Meteor.isClient) { ... }. All files loaded on the client are automatically concatenated and minified when in production mode. In development mode, JavaScript and CSS files are not minified, to make debugging easier. (CSS files are still combined into a single file for consistency between production and development, because changing the CSS file's URL affects how URLs in it are processed.)

    clientディレクトリはサーバー側には読み込まれません。if(Meteor.isClient){ ... }で囲んだ部分も同様です。クライアントに読み込まれたすべてのファイルは、production モードの時には自動的に結合、縮小化されます。developmentモードではJavaScriptとCSSファイルは、デバッグしやすくするために縮小化は行いません。(CSSファイルの場合は,URL変更がCSS読み込みに影響するので、productionとdevelopmentの双方で単一のファイルに結合されています。)

    HTML files in a Meteor application are treated quite a bit differently from a server-side framework. Meteor scans all the HTML files in your directory for three top-level elements: <head>, <body>, and <template>. The head and body sections are separately concatenated into a single head and body, which are transmitted to the client on initial page load.

    MeteorアプリケーションにおけるHTMLファイルの扱いは、サーバーサイドフレームワークにおけるものと異なっています。Meteorはディレクトリ内のHTMLファイルにおいて、3つのトップレベル要素でスキャンします。:<head>, <body>, <template>の3つです。headとbodyはそれぞれ分けられて、一つのheadと一つのbodyに結合されます。それらはページの最初のローディングの際にクライアントに転送されます。

  • server

    Any directory named server is not loaded on the client. Similar to wrapping your code in if (Meteor.isServer) { ... }, except the client never even receives the code. Any sensitive code that you don't want served to the client, such as code containing passwords or authentication mechanisms, should be kept in the server directory.

    serverと名づけられているディレクトリはクライアントにロードされません。if (Meteor.isServer) { ... }で囲まれたコードも同様であり、クライアントが受け取ることがありません。パスワードや認証機能のように、クライアント側に送られたくないコードはserverディレクトリに入れて置かなければなりません。

    Meteor gathers all your JavaScript files, excluding anything under the client, public, and private subdirectories, and loads them into a Node.js server instance. In Meteor, your server code runs in a single thread per request, not in the asynchronous callback style typical of Node. We find the linear execution model a better fit for the typical server code in a Meteor application.

    MeteorはすべてのJavaScriptファイルを、client, public, privateのディレクトリの例外なくNode.jsサーバーのインスタンスにロードします。Meteorでは、サーバーのコードはNode.jsの非同期コールバック処理内ではなく、各リクエスト当たりに一つのスレッドを割り当てています。Meteorアプリケーションにおいては、典型的な直線的な実行モデルが適していると考えています。

  • public

    All files inside a top-level directory called public are served as-is to the client. When referencing these assets, do not include public/ in the URL, write the URL as if they were all in the top level. For example, reference public/bg.png as <img src='/bg.png' />. This is the best place for favicon.ico, robots.txt, and similar files.

    publicというディレクトリ名のトップレベルディレクトリの中にあるファイルは、クライアント側にあるかのように扱われます。それらのassetsを参照する場合は、URLにpublic含めないでください。すべてのファイルがトップレベルにあるものとして書きます。例えば、public/bg.png<img src='/bg.png' />のように書きます。favicon.icorobots.txtはここに置くのがよいでしょう。

  • private

    All files inside a top-level directory called private are only accessible from server code and can be loaded via the Assets API. This can be used for private data files and any files that are in your project directory that you don't want to be accessible from the outside.

    privateというディレクトリ名のトップレベルディレクトリは、サーバーからのみアクセスすることができ、Assets APIを通してロードできます。プライベートなデータファイルや外部からアクセスされたくないファイルの置き場所として使えます。

  • client/compatibility

    This folder is for compatibility JavaScript libraries that rely on variables declared with var at the top level being exported as globals. Files in this directory are executed without being wrapped in a new variable scope. These files are executed before other client-side JavaScript files.

    このフォルダーは互換性のあるJavaScriptライブラリーのファイルのためであり、global変数としてトップレベルでvar宣言している変数を信頼しています。この中のファイルは新しい変数スコープでラップされるることなく実行されます。また、ここにあるファイルは他のクライアント・サイトのJavascriptファイルより以前に実行されます。

  • tests

    Any directory named tests is not loaded anywhere. Use this for any local test code.

    testsという名前のディレクトリはロードされません。ローカル環境のテストコードとして使われます。

  • node_modules

    For compatibility with node.js tools used alongside Meteor, any directory named node_modules is not loaded anywhere. node.js packages installed into node_modules directories will not be available to your Meteor code. Use Npm.depends in your package package.js file for that.

    Meteorと共に使われるnode.jsツールとの互換性のため、node_modulesというディレクトリはどこにもロードされません。node_modulesディレクトリにインストールされたnode.jsパッケージはMeteorのコードからは直接使用できません。package.jsのファイルの中でNpm.dependsを使用してください。

The following directories are also not loaded as part of your app code:

以下のディレクトリもアプリケーションのコードとしてロードされません。

  • Files/directories whose names start with a dot, like .meteor and .git
  • packages/: Used for local packages, covered below
  • programs: For legacy reasons
  • cordova-build-override

Files outside special directories

All JavaScript files outside special directories are loaded on both the client and the server. That's the place for model definitions and other functions. Meteor provides the variables Meteor.isClient and Meteor.isServer so that your code can alter its behavior depending on whether it's running on the client or the server.

CSS and HTML files outside special directories are loaded on the client only, and cannot be used from server code.

Example File Structure

The file structure of your Meteor app is very flexible. Here is an example layout that takes advantage of some of the special folders mentioned above.

lib/                      # common code like collections and utilities
lib/methods.js            # Meteor.methods definitions
lib/constants.js          # constants used in the rest of the code

client/compatibility      # legacy libraries that expect to be global
client/lib/               # code for the client to be loaded first
client/lib/helpers.js     # useful helpers for your client code
client/body.html          # content that goes in the <body> of your HTML
client/head.html          # content for <head> of your HTML: <meta> tags, etc
client/style.css          # some CSS code
client/<feature>.html     # HTML templates related to a certain feature
client/<feature>.js       # JavaScript code related to a certain feature

server/lib/permissions.js # sensitive permissions code used by your server
server/publications.js    # Meteor.publish definitions

public/favicon.ico        # app icon

settings.json             # configuration data to be passed to meteor --settings
mobile-config.js          # define icons and metadata for Android/iOS

You can also model your directory structure after the example apps. Run meteor create --example todos and explore the directories to see where all the files in a real app could go.

File Load Order

It is best to write your application in such a way that it is insensitive to the order in which files are loaded, for example by using Meteor.startup, or by moving load order sensitive code into packages, which can explicitly control both the load order of their contents and their load order with respect to other packages. However, sometimes load order dependencies in your application are unavoidable.

There are several load ordering rules. They are applied sequentially to all applicable files in the application, in the priority given below:

  1. HTML template files are always loaded before everything else
  2. Files beginning with main. are loaded last
  3. Files inside any lib/ directory are loaded next
  4. Files with deeper paths are loaded next
  5. Files are then loaded in alphabetical order of the entire path
nav.html
main.html
client/lib/methods.js
client/lib/styles.js
lib/feature/styles.js
lib/collections.js
client/feature-y.js
feature-x.js
client/main.js

For example, the files above are arranged in the correct load order. main.html is loaded second because HTML templates are always loaded first, even if it begins with main., since rule 1 has priority over rule 2. However, it will be loaded after nav.html because rule 2 has priority over rule 5.

client/lib/styles.js and lib/feature/styles.js have identical load order up to rule 4; however, since client comes before lib alphabetically, it will be loaded first.

Organizing Your Project

There are three main ways to organize your files into features or components. Let's say we have two types of objects in our project: apples and oranges.

Method 1: Root-Level Folders

Since the special client, server, and lib directories work if they are anywhere in the path, you can use top-level folders to organize code into modules:

apples/lib/               # code for apple-related features
apples/client/
apples/server/

oranges/lib/              # code for orange-related features
oranges/client/
oranges/server/

Method 2: Folders inside client/ and server/

lib/apples/               # common code for apples
lib/oranges/              # and oranges

client/apples/            # client code for apples
client/oranges/           # and oranges

server/apples/            # server code for apples
server/oranges/           # and oranges

Method 3: Packages

This is the ultimate in code separation, modularity, and reusability. If you put the code for each feature in a separate package, the code for one feature won't be able to access the code for the other feature except through exports, making every dependency explicit. This also allows for the easiest independent testing of features. You can also publish the packages and use them in multiple apps with meteor add.

packages/apples/package.js     # files, dependencies, exports for apple feature
packages/apples/<anything>.js  # file loading is controlled by package.js

packages/oranges/package.js    # files, dependencies, exports for orange feature
packages/oranges/<anything>.js # file loading is controlled by package.js

Data and security

To read about best practices for managing data and security in Meteor, consult the Meteor Guide:

Authentication and user accounts

認証とユーザーアカウント

Meteor includes Meteor Accounts, a state-of-the-art authentication system. It features secure password login using the bcrypt algorithm, and integration with external services including Facebook, GitHub, Google, Meetup, Twitter, and Weibo. Meteor Accounts defines a Meteor.users collection where developers can store application-specific user data.

MeteorはMeteor Accountsを持っています。 これは最新の認証システムです。 bcryptアルゴリズムをつかったセキュアなパスワードログインと、 Facebook、GitHub、Google、Meetup、Twitter、Weiboなど外部サービスとの連携を機能として備えています。 Meteor AccountsはMeteor.usersコレクションを定義します。 ここには開発者がアプリケーションに特有のユーザーデータを保存することができます。

Meteor also includes pre-built forms for common tasks like login, signup, password change, and password reset emails. You can add Accounts UI to your app with just one line of code. The accounts-ui package even provides a configuration wizard that walks you through the steps to set up the external login services you're using in your app.

Meteorは、ログイン、サインアップ、パスワード変更、パスワードリセットのemailなど、共通のタスクにために、ビルド済みのフォームも持っています。 Accounts UIをたったの一行のコードであなたのアプリに追加することができます。 accounts-uiパッケージはあなたのアプリで使っている外部ログインサービスのセットアップを順番に手助けしてくれる設定ウィザードまで提供しています。

Read about how to manage user accounts in your Meteor app in the Meteor Guide.

Reactivity

Meteor embraces the concept of reactive programming. This means that you can write your code in a simple imperative style, and the result will be automatically recalculated whenever data changes that your code depends on.

Meteorはリアクティブプログラミングのコンセプトを大切にしています。 これは、シンプルな命令形(imperative)のスタイルで書けて、その結果はコードが依存しているデータに変更があった場合はいつでも自動的に再計算されるという意味です。

Tracker.autorun(function () {
  Meteor.subscribe("messages", Session.get("currentRoomId"));
});

This example (taken from a chat room client) sets up a data subscription based on the session variable currentRoomId. If the value of Session.get("currentRoomId") changes for any reason, the function will be automatically re-run, setting up a new subscription that replaces the old one.

この例(チャットルールクライアントからもってきました)はセッション変数currentRoomIdをもとにデータのサブスクリプションを設定しています。 どんな理由であれ、もしSession.get("currentRoomId")の値がかわると、この関数は自動的に再実行され、古いサブスクリプションの入れ替えになる新しいサブスクリプションを設定します。

This automatic recomputation is achieved by a cooperation between Session and Tracker.autorun. Tracker.autorun performs an arbitrary "reactive computation" inside of which data dependencies are tracked, and it will re-run its function argument as necessary. Data providers like Session, on the other hand, make note of the computation they are called from and what data was requested, and they are prepared to send an invalidation signal to the computation when the data changes.

この自動再計算は、SessionTracker.autorunの連携で実現しています。 Tracker.autorunは、内部でデータ依存性が追跡されている、任意の「リアクティブな計算」を実行します。また、必要に応じて、渡された関数引数を再実行します。 Sessionのようなデータプロバイダーは、この他に、それが呼びだされた計算とどのようなデータが要求されたかということを記録し、データが変わった時、無効化のシグナルをその計算へ送り出す準備をします。

This simple pattern (reactive computation + reactive data source) has wide applicability. Above, the programmer is saved from writing unsubscribe/resubscribe calls and making sure they are called at the right time. In general, Meteor can eliminate whole classes of data propagation code which would otherwise clog up your application with error-prone logic.

このシンプルなパターン(リアクティブ計算 + リアクティブデータソース)は、幅広い適用可能性を持っています。 プログラマーは、サブスクライブの停止/再開の呼び出しを書くこと、それが正しいタイミングで実行されるようにすることから開放されます。 通常、Meteorは、あなたのアプリケーションをエラーが起こりやすいロジックだらけにしてしまう、データの伝播(プロパゲーション)クラスを取り除くことができます。

These Meteor functions run your code as a reactive computation:

これらのMeteor関数はあなたのコードをリアクティブ計算として実行します:

And the reactive data sources that can trigger changes are:

また、変更をトリガーできるリアクティブ・データソースは以下のものです:

In addition, the following functions which return an object with a stop method, if called from a reactive computation, are stopped when the computation is rerun or stopped:

加えて、stopメソッド付きでオブジェクトを返す以下の関数は、リアクティブ計算から呼ばれたとき、そのリアクティブ計算が再実行または停止された場合に、停止されます:

Meteor's implementation is a package called Tracker that is fairly short and straightforward. You can use it yourself to implement new reactive data sources.

Meteorの実装は、 Trackerという、かなり短くてわかりやすいパッケージです。 これをつかって、あなた自身でリアクティブなデータソースを実装することができます。

Live HTML templates

HTML templating is central to web applications. With Blaze, Meteor's live page update technology, you can render your HTML reactively, meaning that it will update automatically to track changes in the data used to generate it.

HTMLテンプレートは、ウェブアプリケーションにとって中心的な存在です。 Blazeを用いると、Meteorのライブページアップデート技術により、リアクティブにあなたのHTMLを描画できます。 これは、描画するのに使ったデータの変更を追跡し、自動的に更新するということです。

Read about how to use Blaze in the Meteor Guide.

Using packages

All of the functionality you've read about so far is implemented in standard Meteor packages. This is possible thanks to Meteor's unusually powerful isomorphic package and build system. Isomorphic means the same packages work in the web browser, in mobile apps, and on the server. Packages can also contain plugins that extend the build process, such as coffeescript (CoffeeScript compilation) or templating (compiling HTML templates).

ここまでところ、あたなが読んだ全ての機能は、標準のMeteorパッケージで実装されています。 ここまでできるのは、Meteorの非常にパワフルでisomorphicなパッケージとビルドシステムのおかげです。 isomorphicとは、同じパッケージが、Webブラウザ、モバイルアプリ、サーバーで動くということです。 パッケージは、coffeescript(CoffeeScriptのコンパイル)や、 templating ( HTMLテンプレートのコンパイル)のようなビルド・プロセスを拡張するプラグインを含むこともできます

Anyone can publish a Meteor package, and thousands of community-written packages have been published to date. The easiest way to browse these packages is Atmosphere, by Percolate Studio. You can also use the meteor search and meteor show commands.

You can add packages to your project with meteor add and remove them with meteor remove. Additionally, meteor list will tell you what packages your project is using, and meteor update will update them to the newest versions when possible.

あなたのプロジェクトには、meteor addを利用してパッケージを追加することができます。 また、meteor removeをつかって削除することもできます。 さらに、meteor listで、あなたのプロジェクトがどのパッケージを利用しているか確認することができます。 meteor updateをつかうと、利用可能な場合パッケージを最新バージョンに更新することもできます。

By default all apps include the meteor-base package. This pulls in the packages that make up the core of the Meteor stack. Most apps will have this package.

デフォルトでは、全てのアプリにはmeteor-baseパッケージが含まれています。 これによりMeteorスタックの中核を成すパッケージ群を取り込みます。 ほとんどのアプリをこのパッケージを使うことになるでしょう。

All new apps also start with a set of packages that allow a friendly development experience. For more information about these packages, check out the comments in the packages file.

全ての新しいアプリの作成は、心地よいディベロップメント・エクスペリエンスを提供するための一揃いのパッケージと共に開始されます。 これらのパッケージについては、packages fileのコメントを確認してください。

Meteor uses a single-loading packaging system, meaning that it loads just one version of every package. Before adding or upgrading to a particular version of a package, Meteor uses a constraint solver to check if doing so will cause other packages to break. By default, Meteor will choose conservatively. When adding transitive dependencies (packages that other packages, but not the application itself) depend on, Meteor will try to choose the earlier version.

Meteorは、シングル・ローディング パッケージングシステムを使っています。これは、それぞれのパッケージに対して、唯一のバージョンをロードするという意味です。 特定のバージョンのパッケージを追加や更新する前に、Meteorはconstraint solverをつかって、その操作が他のパッケージを壊さないか確認します。 Meteorはデフォルトでは保守的な選択をします。 間接的な依存パッケージ(そのアプリケーション自身ではなく、そこから他のパッケージを依存パッケージとして取り込む間接的なパッケージ)を追加する時、Meteorは最も古いバージョンを選択します。

In addition to the packages in the official Meteor release being used by your app, meteor list and meteor add also search the packages directory at the top of your app. You can also use the packages directory to break your app into subpackages for your convenience, or to test packages that you might want to publish. See Writing Packages. If you wish to add packages outside of your app's folder structure, set the environment variable PACKAGE_DIRS to a colon-delimited list of paths.

あなたのアプリに使われているオフィシャルなMeteorリリースに含まれるパッケージに加えて、meteor listmeteor add は、あなたのアプリの直下におかれたpackagesディレクトリも同様に検索します。 packages ディレクトリはあなたのアプリをサブパッケージに分解するための便利な方法です。公開したいパッケージをテストするためにも使うことができます。 Writing Packagesを参考にしてください。 もしパッケージをあなたのアプリのフォルダ構成の外側で追加したいのであれば、コロン区切りのパスのリストを環境変数PACKAGE_DIRSに設定してください。

Namespacing

Meteor's namespacing support makes it easy to write large applications in JavaScript. Each package that you use in your app exists in its own separate namespace, meaning that it sees only its own global variables and any variables provided by the packages that it specifically uses. Here's how it works.

Meteorの名前空間サポートはJavaScriptでの大規模アプリケーションの作成を容易にします。 あなたのアプリで利用するそれぞれのパッケージは、それぞれ独自に分けられた名前空間の中に存在しています。 つまり、各パッケージは自分のグローバル変数と、そこから明示的に利用しているパッケージの変数のみを参照するということです。 以下、どのように動くかという説明です。

When you declare a top-level variable, you have a choice. You can make the variable File Scope or Package Scope.

トップレベルの変数を宣言するとき、あなたには選択肢があります。 ファイル・スコープにするか、またはパッケージ・スコープにするかです。

// File Scope. This variable will be visible only inside this
// one file. Other files in this app or package won't see it.
var alicePerson = {name: "alice"};

// Package Scope. This variable is visible to every file inside
// of this package or app. The difference is that 'var' is
// omitted.
bobPerson = {name: "bob"};

// ファイルスコープ。この変数は、この1ファイルの中でのみ参照可能です。
// このアプリの他のファイルやパッケージからは参照するとができません。
var alicePerson = {name: "alice"};

// パッケージスコープ。 この変数は、このパッケージまたはアプリのどのファイルからも参照できます。
// 違いは、'var' が省略されている点です。
bobPerson = {name: "bob"};

Notice that this is just the normal JavaScript syntax for declaring a variable that is local or global. Meteor scans your source code for global variable assignments and generates a wrapper that makes sure that your globals don't escape their appropriate namespace.

これはJavaScriptの通常の、ローカルまたは グローバル変数を宣言するシンタックスであるということに注意をしてください。 Meteorはあなたのソースコードをスキャンして、グローバル変数の割当てを探し、 あなたのグローバル変数が正しい名前空間から漏れないようにするためのラッパーを生成します。

In addition to File Scope and Package Scope, there are also Exports. An export is a variable that a package makes available to you when you use it. For example, the email package exports the Email variable. If your app uses the email package (and only if it uses the email package!) then your app can see Email and you can call Email.send. Most packages have only one export, but some packages might have two or three (for example, a package that provides several classes that work together).

ファイルスコープとパッケージスコープに加えて、エクスポートもあります。 エクスポートとは、パッケージがあなたがつかえるように、ある変数を提供するための仕組みです。 たとえば、emailパッケージはEmail変数をエクスポートします。 もしあなたのアプリがemailパッケージを使う(そして、 あなたがemailパッケージだけを使う!)のなら、 あなたのアプリはEmailを参照でき、Email.sendを呼ぶことができます。 ほとんどのパッケージはエクスポートを1つだけ持っていますが、 いくつかのパッケージはエクスポートを2つか3つもっていることもあります。 (例えば、互いに動作する幾つかのクラスを提供するパッケージなど)

You see only the exports of the packages that you use directly. If you use package A, and package A uses package B, then you only see package A's exports. Package B's exports don't "leak" into your namespace just because you used package A. This keeps each namespace nice and tidy. Each app or package only sees their own globals plus the APIs of the packages that they specifically asked for.

あなたは、直接つかうパッケージのエクスポートだけ見ることができます。 もしあなたがパッケージAを使い、パッケージAがパッケージBを使っているとき、 見えるのはパッケージAのエクスポートだけです。 パッケージBのエクスポートはあなたがパッケージAをつかっているからといって、 あなたの名前空間に"漏れ"たりしません。 こうして、それぞれの名前空間はきれいに保たれます。 各アプリまたはパッケージは、それぞれ各自のグローバル変数と、明示的に指定したパッケージのAPIのみ、見ることができるのです。

When debugging your app, your browser's JavaScript console behaves as if it were attached to your app's namespace. You see your app's globals and the exports of the packages that your app uses directly. You don't see the variables from inside those packages, and you don't see the exports of your transitive dependencies (packages that aren't used directly by your app, but that are used by packages that are used by your app).

あなたのアプリをデバッグするとき、ブラウザのJavaScriptコンソールは、あたかもあなたのアプリの名前空間に接続されたかのように振る舞います。 あなたのアプリのグローバル変数とあなたのアプリが直接使うパッケージのエクスポート変数を見ることができます。 これら直接利用するパッケージの内側の変数や、間接的な依存性 (直接あなたのアプリから利用していないが、あなたのアプリが使うパッケージがつかっているパッケージ)のエクスポート変数は見ることができません。

If you want to look inside packages from inside your in-browser debugger, you've got two options:

もし、ブラウザの中のデバッガからパッケージの中身が見たいのなら、2つのオプションがあります:

  • Set a breakpoint inside package code. While stopped on that breakpoint, the console will be in the package's namespace. You'll see the package's package-scope variables, imports, and also any file-scope variables for the file you're stopped in.

    パッケージのコードにブレークポイントをセットする。ブレークポイントで止まっている間は、コンソールはパッケージの名前空間にいます。 パッケージスコープの変数、インポート、それに止めたファイル内の全てのファイルスコープ変数を見ることができます。

  • If a package foo is included in your app, regardless of whether your app uses it directly, its exports are available in Package.foo. For example, if the email package is loaded, then you can access Package.email.Email.send even from namespaces that don't use the email package directly.

    もし、パッケージfooがあなたのアプリに入っていたら、あなたのアプリがそれを直接つかうかどうかに関わらず、 それのエクスポートはPackage.fooの中で利用可能です。例えば、email パッケージが読み込まれたら、 たとえ、emailパッケージを直接使わない名前空間からでも、Package.email.Email.send にアクセス可能です。

When declaring functions, keep in mind that function x () {} is just shorthand for var x = function x () {} in JavaScript. Consider these examples:

functionを宣言する時、JavaScriptでは、function x () {}は、 単にvar x = function x () {}の省略形であるということに注意してください。 これらの例を考えてみてください。

// This is the same as 'var x = function x () ...'. So x() is
// file-scope and can be called only from within this one file.
function x () { ... }

// No 'var', so x() is package-scope and can be called from
// any file inside this app or package.
x = function () { ... }
// これは 'var x = function x () ...' と同じ。つまり、x() は
// ファイルスコープであり、このファイルの中だけで呼び出すことができます。
function x () { ... }

// 'var' がついていません, つまり x() はパッケージスコープで、
// このアプリまたはパッケージのどこからでも呼び出すことができます。
x = function () { ... }

Technically speaking, globals in an app (as opposed to in a package) are actually true globals. They can't be captured in a scope that is private to the app code, because that would mean that they wouldn't be visible in the console during debugging! This means that app globals actually end up being visible in packages. That should never be a problem for properly written package code (since the app globals will still be properly shadowed by declarations in the packages). You certainly shouldn't depend on this quirk, and in the future Meteor may check for it and throw an error if you do.

厳密にいうと、アプリの中(パッケージとは違い)のグローバル変数は、実際のところ、本当にグローバル変数です。 これらの変数をアプリのコードに対してプライベートなスコープに閉じ込めることができません。 なぜなら、デバッグするときにコンソールから見えなくなってしまうからです。 これはつまり、アプリのグローバル変数は他のパッケージに見えてしまうということです。 このことは正しく書かれたパッケージのコードには、決して問題になるようなことはありません。 (なぜなら、アプリのグローバル変数は、パッケージの中の変数宣言によって正しくシャドーイングされるからです) 当然のことながら、この変わった挙動に依存するべきではありません。 Meteorは将来、チェックをしてもしあなたがそんなことをしていたらエラーを投げるかも知れません。

Deploying

To learn how to deploy Meteor apps, read the deployment article in the Meteor Guide.

Writing packages

Writing Meteor packages is easy. To initialize a meteor package, run meteor create --package username:packagename, where username is your Meteor Developer username. This will create a package from scratch and prefill the directory with a package.js control file and some javascript. By default, Meteor will take the package name from the name of the directory that contains the package.js file. Don't forget to run meteor add [packagename], even if the package is internal to the app, in order to use it.

Meteorのパッケージを書くのは簡単です。 meteorパッケージを初期化するには、meteor create --package username:packagenameを実行してください。 username は、あなたのMeteor Developer usernameです。 これはパッケージをスクラッチで作成し、ディレクトリーに、package.jsコントロールファイルといくつかのJavaScriptを生成します。 デフォルトでは、Meteorはpackage.jsファイルが入っているディレクトリーの名前をパッケージ名として使います。 パッケージを使うためには、仮にそのパッケージがアプリに内部的なものであっても、 利用するためにはmeteor add [packagename]を実行するのをわすれないでください。

Meteor promises repeatable builds for both packages and applications. This means that, if you built your package on a machine, then checked the code into a repository and checked it out elsewhere, you should get the same result. In your package directory, you will find an automatically generated .versions file. This file specifies the versions of all packages used to build your package and is part of the source. Check it into version control to ensure repeatable builds across machines.

Meteorはパッケージとアプリケーションの両方に繰り返し実行可能なビルドを保証します。 これはつまり、あなたがパッケージをあるコンピューターでつくり、リポジトリに入れ、そしてどこかでチェックアウトしたとして、同じ結果になるということです。 あなたのパッケージ・ディレクトリに自動生成された.versionsファイルがつくられます。 このファイルはソースの一部であり、あなたのパッケージをビルドするために使われるパッケージを指定します。 コンピューターをまたいで繰り返し可能なビルドが出来るよう、このファイルをバージョン管理システムにチェックインしてください。

Sometimes, packages do not just stand on their own, but function in the context of an app (specifically, packages in the packages directory of an app). In that case, the app's context will take precedence. Rather than using the .versions file as a guide, we will build the package with the same dependencies as used by the app (we think that, in practice, it would be confusing to find your local packages built with different versions of things).

パッケージは、時としてそれ自体では成立せず、アプリのコンテキストの中で機能します。(具体的には、アプリのpackagesディレクトリ内のパッケージ) この場合、アプリのコンテキストが優先されます。.versions ファイルをガイドとして使うのではなく、アプリに使われるのと同じ依存性をつかってパッケージをビルドします。 (異なったバージョンをつかってビルドされたパッケージがローカルパッケージにあったら、実際問題として、混乱を招くと思います。)

Meteor uses extended semver versioning for its packages: that means that the version number has three parts separated by dots: major version, minor version and patch version (for example: 1.2.3) with an optional pre-release version. You can read more about it on semver.org. Additionally, because some meteor packages wrap external libraries, Meteor supports the convention of using _ to denote a wrap number.

Meteorは、拡張されたsemverバージョニングをMeteorのパッケージに対して使います。 これは、バージョン番号にドットで句切られた3つの部分があるということです。 メジャーバジョン、マイナーバージョン、パッチバージョン(例えば、1.2.3)と、オプションでプレリリースバージョンが付きます。 詳細はsemver.orgを読んで下さい。 さらに、いくつかのmeteorパッケージは外部ライブラリを包含しているので、Meteorは、ラップバージョンを示すため、 _ をつかうという規約をサポートしています。

You can read more about package.js files in the API section.

package.jsファイルについて、APIのセクションで詳細を確認してください。

A word on testing: since testing is an important part of the development process, there are two common ways to test a package:

テストは開発プロセスのなかの重要な部分なため、テストについて一言いっておきます。 パッケージをテストするのに、二つの一般的な方法があります:

  • Integration tests (putting a package directly into an application, and writing tests against the application) is the most common way to test a package. After creating your package, add it to your app's /packages directory and run meteor add. This will add your package to your app as a local package. You can then test and run your app as usual. Meteor will detect and respond to changes to your local package, just as it does to your app files.

    インテグレーションテスト(パッケージ・ディレクトリをアプリケーションに入れ、テストをアプリケーションに対して書く)は最も一般的な、パッケージをテストする方法です。 あなたのパッケージを作った後、それをあなたのアプリの/packagesディレクトリに加え、meteor addを実行してください。 この操作はパッケージをアプリのローカルパッケージに追加します。その後あなたのアプリのテストや実行をいつものようにすることができます。 Meteorはあなたのローカルパッケージへの変更を、アプリのファイルに対して行われたのと同じように、検出し、応答します。

  • Unit tests are run with the command meteor test-packages package-name. As described in the package.js section, you can use the package.js file to specify where your unit tests are located. If you have a repository that contains only the package source, you can test your package by specifying the path to the package directory (which must contain a slash), such as meteor test-packages ./.

    ユニットテストは、meteor test-packages package-nameコマンドで実行されます。 package.jsセクションで説明されているように、package.jsファイルはあなたのユニットテストの場所を指定するために使えます。 もし、パッケージのソースだけを含むリポジトリがあるなら、パッケージのディレクトリ(スラッシュを含んでいなければいけません)を指定することでパッケージをテストすることができます。 たとえば、meteor test-packages ./のようにしてください。

To publish a package, run meteor publish from the package directory. There are some extra restrictions on published packages: they must contain a version (Meteor packages are versioned using strict semver versioning) and their names must be prefixed with the username of the author and a colon, like so: iron:router. This namespacing allows for more descriptive and on-topic package names.

パッケージを公開するためには、パッケージディレクトリから、meteor publish を実行してください。 パッケージを公開するためにはいくつか追加の制限があります。それは、パッケージはバージョン (Meteorパッケージはsemver バージョニングを使って厳格にバージョニングされています) を持っていなければいけません。また、iron:routerのように、作者のユーザー名とコロンがパッケージ名の前についていなければいけません。 この名前付けルールににより、より描写的でまとまりのあるパッケージ名にすることができます。

The Meteor API

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.

JavaScriptコードは2つの環境で動きます。一つはclientすなわちブラウザです。もう一つは、serverすなわちサーバ上のNode.jsの中です。このAPI仕様書ではそれぞれの関数がどちらで動くものか明記されます。クライアントとサーバの両方で動く場合はAnywhereと示されます。

Meteor Core

Anywhere
Meteor.isClient

Boolean variable. True if running in client environment.

真偽値。クライアント環境の場合Trueになる。

Anywhere
Meteor.isServer

Boolean variable. True if running in server environment.

真偽値。サーバ環境の場合Trueになる。

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 kept in the server directory.

Meteor.isServerはそのコードがどこで動くかを制限することには使えますが、そのコードがクライアント側に送られることは阻止しません。クライアントに送りたくない秘密のコードserverに格納すべきです。例えば、パスワードや認証のメカニズムが含まれているコードなどが該当します。

Anywhere
Meteor.isCordova

Boolean variable. True if running in a Cordova mobile environment.

真偽値。Cordovaモバイル環境の場合Trueになる

Anywhere
Meteor.startup(func)

Run code when a client or a server starts.

クライアントやサーバが起動したときにコードを実行する。

Arguments

func Function

A function to run on startup.

起動時に実行する関数

On a server, the function will run as soon as the server process is finished starting. On a client, the function will run as soon as the DOM is ready.

サーバー上では、サーバーの開始が完了すると同時に関数が実行される。クライアント上では、DOMが完了すると同時に関数が実行される。

The startup callbacks are called in the same order as the calls to Meteor.startup were made.

startupのコールバック関数はMeteor.startupの呼びだされた順番によって実行される。

On a client, startup callbacks from packages will be called first, followed by <body> templates from your .html files, followed by your application code.

// On server startup, if the database is empty, create some initial data.
if (Meteor.isServer) {
  Meteor.startup(function () {
    if (Rooms.find().count() === 0) {
      Rooms.insert({name: "Initial room"});
    }
  });
}

Anywhere
Meteor.wrapAsync(func, [context])

Wrap a function that takes a callback function as its final parameter. The signature of the callback of the wrapped function should be function(error, result){}. On the server, the wrapped function can be used either synchronously (without passing a callback) or asynchronously (when a callback is passed). On the client, a callback is always required; errors will be logged if there is no callback. If a callback is provided, the environment captured when the original function was called will be restored in the callback.

コールバック関数を引数の最後に受け取る関数をラップします。ラップされた関数に代入されるコールバック関数に特徴的な書き方はfunction(error, result){}です。サーバー上では、ラップされた関数は同期的(コールバック関数を設定しない)にも非同期的(コールバック関数を設定する)にも使えます。

Arguments

func Function

A function that takes a callback as its final parameter

引数の最後にコールバック関数を受け取る関数

context Object

Optional this object against which the original function will be invoked

ラップされる前の関数オブジェクトが代入されるthis

Anywhere
Meteor.absoluteUrl([path], [options])

Generate an absolute URL pointing to the application. The server reads from the ROOT_URL environment variable to determine where it is running. This is taken care of automatically for apps deployed with meteor deploy, but must be provided when using meteor build.

アプリケーションを指す絶対URLを生成します。サーバーは実行されている場所を特定するために環境変数ROOT_URLを参照します。 これは、meteor deployをつかってデプロイされたアプリには自動的に設定されますが、meteor buildを使う時は設定しなければなりません。

Arguments

path String

A path to append to the root URL. Do not include a leading "/".

ルートURLにつなげるパス。先頭に"/"を付けないでください。

Options

secure Boolean

Create an HTTPS URL.

HTTPS URLを作ります。

replaceLocalhost Boolean

Replace localhost with 127.0.0.1. Useful for services that don't recognize localhost as a domain name.

localhostを127.0.0.1に置き換えます。localhostをドメイン名として認識しないサービスに便利です。

rootUrl String

Override the default ROOT_URL from the server environment. For example: "http://foo.example.com"

サーバーの環境変数のROOT_URLを上書きします。例: "http://foo.example.com"

Anywhere
Meteor.settings

Meteor.settings contains deployment-specific configuration options. You can initialize settings by passing the --settings option (which takes the name of a file containing JSON data) to meteor run or meteor deploy. When running your server directly (e.g. from a bundle), you instead specify settings by putting the JSON directly into the METEOR_SETTINGS environment variable. If the settings object contains a key named public, then Meteor.settings.public will be available on the client as well as the server. All other properties of Meteor.settings are only defined on the server. You can rely on Meteor.settings and Meteor.settings.public being defined objects (not undefined) on both client and server even if there are no settings specified. Changes to Meteor.settings.public at runtime will be picked up by new client connections.

Meteor.settingsは、デプロイメント固有の設定オプションが入っています。 settingsはmeteor runまたはmeteor deploy--settingsオプション(JSONデータを含んだファイルの名前をセットします)で渡して初期化することができます。 あなたのサーバーを直接実行するとき(たとえば bundleからの実行時)、代わりに環境変数METEOR_SETTINGSに直接JSONをセットすることで、settingsを設定します。 settingsオブジェクトにpublicという名前のキーが含まれている場合は、Meteor.settings.publicがサーバーだけでなくクライアントでも利用可能になります。 その他全てのMeteor.settingsのプロパティは、サーバーでのみ利用可能です。 例えsettingsを指定しなくても、クライアントとサーバーの両方にMeteor.settingsMeteor.settings.publicが(undefinedにならず)オブジェクトとして利用可能であるということに依存して大丈夫です。 Meteor.settings.publicへの実行時の変更は、新たなクライアントの接続時に拾われます。

Anywhere
Meteor.release

Meteor.release is a string containing the name of the release with which the project was built (for example, "1.2.3"). It is undefined if the project was built using a git checkout of Meteor.

Meteor.releaseは、プロジェクトがビルドにつかったリリース名を含んだ文字列です。(例えば、"1.2.3") これは、もしプロジェクトがMeteorをgitからチェックアウトしてビルドするとundefinedになります。

Publish and subscribe

These functions control how Meteor servers publish sets of records and how clients can subscribe to those sets.

Server
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 all connected clients.

配信するデータの名称。nullがセットされた場合、配信されるデータには名称が設定されず、自動的に接続している全てのクライアントに配信されます。

func Function

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

クライアントから購読されるたびにサーバで実行される関数。関数の処理中でthisは、後述する配信を制御するオブジェクトを指し示します。クライアント側でsubscribeメソッドの同引数を省略すると、サーバ側と同じ関数が実行されます。

To publish records to clients, call Meteor.publish on the server with two parameters: the name of the record set, and a publish function that Meteor will call each time a client subscribes to the name.

Publish functions can return a Collection.Cursor, in which case Meteor will publish that cursor's documents to each subscribed client. You can also return an array of Collection.Cursors, in which case Meteor will publish all of the cursors.

If you return multiple cursors in an array, they currently must all be from different collections. We hope to lift this restriction in a future release.

// server: publish the rooms collection, minus secret info.
Meteor.publish("rooms", function () {
  return Rooms.find({}, {fields: {secretInfo: 0}});
});

// ... and publish secret info for rooms where the logged-in user
// is an admin. If the client subscribes to both streams, the records
// are merged together into the same documents in the Rooms collection.
Meteor.publish("adminSecretInfo", function () {
  return Rooms.find({admin: this.userId}, {fields: {secretInfo: 1}});
});

// publish dependent documents and simulate joins
Meteor.publish("roomAndMessages", function (roomId) {
  check(roomId, String);
  return [
    Rooms.find({_id: roomId}, {fields: {secretInfo: 0}}),
    Messages.find({roomId: roomId})
  ];
});

Alternatively, a publish function can directly control its published record set by calling the functions added (to add a new document to the published record set), changed (to change or clear some fields on a document already in the published record set), and removed (to remove documents from the published record set). These methods are provided by this in your publish function.

If a publish function does not return a cursor or array of cursors, it is assumed to be using the low-level added/changed/removed interface, and it must also call ready once the initial record set is complete.

Example:

// server: publish the current size of a collection
Meteor.publish("counts-by-room", function (roomId) {
  var self = this;
  check(roomId, String);
  var count = 0;
  var initializing = true;

  // observeChanges only returns after the initial `added` callbacks
  // have run. Until then, we don't want to send a lot of
  // `self.changed()` messages - hence tracking the
  // `initializing` state.
  var handle = Messages.find({roomId: roomId}).observeChanges({
    added: function (id) {
      count++;
      if (!initializing)
        self.changed("counts", roomId, {count: count});
    },
    removed: function (id) {
      count--;
      self.changed("counts", roomId, {count: count});
    }
    // don't care about changed
  });

  // Instead, we'll send one `self.added()` message right after
  // observeChanges has returned, and mark the subscription as
  // ready.
  initializing = false;
  self.added("counts", roomId, {count: count});
  self.ready();

  // Stop observing the cursor when client unsubs.
  // Stopping a subscription automatically takes
  // care of sending the client any removed messages.
  self.onStop(function () {
    handle.stop();
  });
});

// client: declare collection to hold count object
Counts = new Mongo.Collection("counts");

// client: subscribe to the count for the current room
Tracker.autorun(function () {
  Meteor.subscribe("counts-by-room", Session.get("roomId"));
});

// client: use the new collection
console.log("Current room has " +
            Counts.findOne(Session.get("roomId")).count +
            " messages.");

// server: sometimes publish a query, sometimes publish nothing
Meteor.publish("secretData", function () {
  if (this.userId === 'superuser') {
    return SecretData.find();
  } else {
    // Declare that no data is being published. If you leave this line
    // out, Meteor will never consider the subscription ready because
    // it thinks you're using the added/changed/removed interface where
    // you have to explicitly call this.ready().
    return [];
  }
});

Since publish functions usually expect particular types as arguments, use check liberally to ensure the arguments have the correct types and structure.

Meteor will emit a warning message if you call Meteor.publish in a project that includes the autopublish package. Your publish function will still work.

Server
this.userId

Access inside the publish function. The id of the logged-in user, or null if no user is logged in.

This is constant. However, if the logged-in user changes, the publish function is rerun with the new value.

Server
this.added(collection, id, fields)

Call inside the publish function. Informs the subscriber that a document has been added to the record set.

Arguments

collection String

The name of the collection that contains the new document.

id String

The new document's ID.

fields Object

The fields in the new document. If _id is present it is ignored.

Server
this.changed(collection, id, fields)

Call inside the publish function. Informs the subscriber that a document in the record set has been modified.

Arguments

collection String

The name of the collection that contains the changed document.

id String

The changed document's ID.

fields Object

The fields in the document that have changed, together with their new values. If a field is not present in fields it was left unchanged; if it is present in fields and has a value of undefined it was removed from the document. If _id is present it is ignored.

Server
this.removed(collection, id)

Call inside the publish function. Informs the subscriber that a document has been removed from the record set.

Arguments

collection String

The name of the collection that the document has been removed from.

id String

The ID of the document that has been removed.

Server
this.ready()

Call inside the publish function. Informs the subscriber that an initial, complete snapshot of the record set has been sent. This will trigger a call on the client to the onReady callback passed to Meteor.subscribe, if any.

Server
this.onStop(func)

Call inside the publish function. Registers a callback function to run when the subscription is stopped.

Arguments

func Function

The callback function

If you call observe or observeChanges in your publish handler, this is the place to stop the observes.

Server
this.error(error)

Call inside the publish function. Stops this client's subscription, triggering a call on the client to the onStop callback passed to Meteor.subscribe, if any. If error is not a Meteor.Error, it will be sanitized.

Arguments

error Error

The error to pass to the client.

Server
this.stop()

Call inside the publish function. Stops this client's subscription and invokes the client's onStop callback with no error.

Server
this.connection

Access inside the publish function. The incoming connection for this subscription.

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

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

データの購読登録を行います。返却されるオブジェクトは、stop()メソッドとready()メソッドを提供します。

Arguments

name String

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

購読するデータの名称。サーバ側で同じ名称が設定されたpublish()メソッドが呼び出されます。

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 argument to onStop. If a function is passed instead of an object, it is interpreted as an onReady callback.

任意で設定可能。onStopメソッドとonReadyメソッドを含めることができます。エラーが発生した場合はonStopメソッドの引数となります。オブジェクトの代わりに関数が渡された場合、onReadyメソッドのコールバック関数として解釈されます。

When you subscribe to a record set, it tells the server to send records to the client. The client stores these records in local Minimongo collections, with the same name as the collection argument used in the publish handler's added, changed, and removed callbacks. Meteor will queue incoming records until you declare the Mongo.Collection on the client with the matching collection name.

// okay to subscribe (and possibly receive data) before declaring
// the client collection that will hold it.  assume "allplayers"
// publishes data from server's "players" collection.
Meteor.subscribe("allplayers");
...
// client queues incoming players records until ...
...
Players = new Mongo.Collection("players");

The client will see a document if the document is currently in the published record set of any of its subscriptions.

The onReady callback is called with no arguments when the server marks the subscription as ready. The onStop callback is called with a Meteor.Error if the subscription fails or is terminated by the server. If the subscription is stopped by calling stop on the subscription handle or inside the publication, onStop is called with no arguments.

Meteor.subscribe returns a subscription handle, which is an object with the following properties:

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()

True if the server has marked the subscription as ready. A reactive data source.

subscriptionId

The id of the subscription this handle is for. When you run Meteor.subscribe inside of Tracker.autorun, the handles you get will always have the same subscriptionId field. You can use this to deduplicate subscription handles if you are storing them in some data structure.

If you call Meteor.subscribe within a reactive computation, for example using Tracker.autorun, the subscription will automatically be cancelled when the computation is invalidated or stopped; it's not necessary to call stop on subscriptions made from inside autorun. However, if the next iteration of your run function subscribes to the same record set (same name and parameters), Meteor is smart enough to skip a wasteful unsubscribe/resubscribe. For example:

Tracker.autorun(function () {
  Meteor.subscribe("chat", {room: Session.get("current-room")});
  Meteor.subscribe("privateMessages");
});

This subscribes you to the chat messages in the current room and to your private messages. When you change rooms by calling Session.set("current-room", "new-room"), Meteor will subscribe to the new room's chat messages, unsubscribe from the original room's chat messages, and continue to stay subscribed to your private messages.

If more than one subscription sends conflicting values for a field (same collection name, document ID, and field name), then the value on the client will be one of the published values, chosen arbitrarily.

Methods

Methods are remote functions that Meteor clients can invoke.

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

辞書のキーはメソッド名で、バリューは関数です。

Example:

Meteor.methods({
  foo: function (arg1, arg2) {
    check(arg1, String);
    check(arg2, [Number]);

    // .. do stuff ..

    if (/* you want to throw an error */) {
      throw new Meteor.Error("pants-not-found", "Can't find my pants");
    }

    return "some return value";
  },

  bar: function () {
    // .. do other stuff ..
    return "baz";
  }
});

Calling methods on the server defines functions that can be called remotely by clients. They should return an EJSON-able value or throw an exception. Inside your method invocation, this is bound to a method invocation object, which provides the following:

  • isSimulation: a boolean value, true if this invocation is a stub.
  • unblock: when called, allows the next method from this client to begin running.
  • userId: the id of the current user.
  • setUserId: a function that associates the current client with a user.
  • connection: on the server, the connection this method call was received on.

Calling methods on the client defines stub functions associated with server methods of the same name. You don't have to define a stub for your method if you don't want to. In that case, method calls are just like remote procedure calls in other systems, and you'll have to wait for the results from the server.

If you do define a stub, when a client invokes a server method it will also run its stub in parallel. On the client, the return value of a stub is ignored. Stubs are run for their side-effects: they are intended to simulate the result of what the server's method will do, but without waiting for the round trip delay. If a stub throws an exception it will be logged to the console.

You use methods all the time, because the database mutators (insert, update, remove) are implemented as methods. When you call any of these functions on the client, you're invoking their stub version that update the local cache, and sending the same write request to the server. When the server responds, the client updates the local cache with the writes that actually occurred on the server.

You don't have to put all your method definitions into a single Meteor.methods call; you may call it multiple times, as long as each method has a unique name.

ひとつのMeteor.methods呼び出しにメソッド定義全てを置く必要はありません。ユニークな名前を各メソッドが持つ限り、あなたはこれを複数回呼び出すでしょう。

Since methods usually expect particular types as arguments, use check liberally to ensure your method arguments have the correct types and structure.

If a client calls a method and is disconnected before it receives a response, it will re-call the method when it reconnects. This means that a client may call a method multiple times when it only means to call it once. If this behavior is problematic for your method, consider attaching a unique ID to each method call on the client, and checking on the server whether a call with this ID has already been made.

Anywhere
this.userId

The id of the user that made this method call, or null if no user was logged in.

The user id is an arbitrary string — typically the id of the user record in the database. You can set it with the setUserId function. If you're using the Meteor accounts system then this is handled for you.

Server
this.setUserId(userId)

Set the logged in user.

Arguments

userId String or null

The value that should be returned by userId on this connection.

Call this function to change the currently logged in user on the connection that made this method call. This simply sets the value of userId for future method calls received on this connection. Pass null to log out the connection.

If you are using the built-in Meteor accounts system then this should correspond to the _id field of a document in the Meteor.users collection.

setUserId is not retroactive. It affects the current method call and any future method calls on the connection. Any previous method calls on this connection will still see the value of userId that was in effect when they started.

Anywhere
this.isSimulation

Access inside a method invocation. Boolean value, true if this invocation is a stub.

Server
this.unblock()

Call inside a method invocation. Allow subsequent method from this client to begin running in a new fiber.

On the server, methods from a given client run one at a time. The N+1th invocation from a client won't start until the Nth invocation returns. However, you can change this by calling this.unblock. This will allow the N+1th invocation to start running in a new fiber.

Server
this.connection

Access inside a method invocation. The connection that this method was received on. null if the method is not associated with a connection, eg. a server initiated method call.

Anywhere
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 method to determine the appropriate action to take, instead of attempting to parse the reason or details fields. For example:

文字列はエラーを特定するユニークなものとして表現します。この文字列は、reasonやdetailsをパースしようとする代わりに適切なアクションを決定するためのメソッドの呼び出し元によって使われるべきです。例えば:

// 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 this field.

レガシーな理由のため、いくつかのビルトインなMeteorはエラー処理の順番確認のように機能します。

reason String

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

任意。人間が読んで理解できるエラーの要約。

details String

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 a server will send to the client. If a method function throws a different exception, then it will be mapped to a sanitized version on the wire. Specifically, if the sanitizedError field on the thrown error is set to a Meteor.Error, then that error will be sent to the client. Otherwise, if no sanitized version is available, the client gets Meteor.Error(500, 'Internal server error').

Anywhere
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 to invoke a method. It will run the method on the server. If a stub is available, it will also run the stub on the client. (See also Meteor.apply, which is identical to Meteor.call except that you specify the parameters as an array instead of as separate arguments and you can specify a few options controlling how the method is executed.)

If you include a callback function as the last argument (which can't be an argument to the method, since functions aren't serializable), the method will run asynchronously: it will return nothing in particular and will not throw an exception. When the method is complete (which may or may not happen before Meteor.call returns), the callback will be called with two arguments: error and result. If an error was thrown, then error will be the exception object. Otherwise, error will be undefined and the return value (possibly undefined) will be in result.

// async call
Meteor.call('foo', 1, 2, function (error, result) { ... } );

If you do not pass a callback on the server, the method invocation will block until the method is complete. It will eventually return the return value of the method, or it will throw an exception if the method threw an exception. (Possibly mapped to 500 Server Error if the exception happened remotely and it was not a Meteor.Error exception.)

// sync call
var result = Meteor.call('foo', 1, 2);

On the client, if you do not pass a callback and you are not inside a stub, call will return undefined, and you will have no way to get the return value of the method. That is because the client doesn't have fibers, so there is not actually any way it can block on the remote execution of a method.

Finally, if you are inside a stub on the client and call another method, the other method is not executed (no RPC is generated, nothing "real" happens). If that other method has a stub, that stub stands in for the method and is executed. The method call's return value is the return value of the stub function. The client has no problem executing a stub synchronously, and that is why it's okay for the client to use the synchronous Meteor.call form from inside a method body, as described earlier.

Meteor tracks the database writes performed by methods, both on the client and the server, and does not invoke asyncCallback until all of the server's writes replace the stub's writes in the local cache. In some cases, there can be a lag between the method's return value being available and the writes being visible: for example, if another method still outstanding wrote to the same document, the local cache may not be up to date until the other method finishes as well. If you want to process the method's result as soon as it arrives from the server, even if the method's writes are not available yet, you can specify an onResultReceived callback to Meteor.apply.

Anywhere
Meteor.apply(name, args, [options], [asyncCallback])

Invoke a method passing an array of arguments.

Arguments

name String

Name of method to invoke

呼び出すためのメソッド名

args Array of EJSON-able Objects

Method arguments

asyncCallback Function

Optional callback; same semantics as in Meteor.call.

Options

wait Boolean

(Client only) If true, don't send this method until all previous method calls have completed, and don't send any subsequent method calls until this one is completed.

onResultReceived Function

(Client only) This callback is invoked with the error or result of the method (just like asyncCallback) as soon as the error or result is available. The local cache may not yet reflect the writes performed by the method.

Meteor.apply is just like Meteor.call, except that the method arguments are passed as an array rather than directly as arguments, and you can specify options about how the client executes the method.

DDPRateLimiter

Customize rate limiting for methods and subscriptions.

メソッドとsubscriptionのレートリミットをカスタマイズします。

By default, DDPRateLimiter is configured with a single rule. This rule limits login attempts, new user creation, and password resets to 5 attempts every 10 seconds per connection. It can be removed by calling Accounts.removeDefaultRateLimit().

デフォルトでは、DDPRateLimiterには1つのルールが設定されています。そのルールは ログイン、ユーザ作成、パスワードリセットをコネクションあたり10秒間に5回に制限します。 そのルールはAccounts.removeDefaultRateLimit()で削除することができます。

DDPRateLimiter.addRule(matcher, numRequests, timeInterval)

Add a rule that matches against a stream of events describing method or subscription attempts. Each event is an object with the following properties:

メソッドやsubscriptionの試行を記述するイベントにマッチするルールを追加する。それぞれのイベンなは次のプロパティを持つイベントである:

  • type: Either "method" or "subscription"
  • type: "method"もしくは"subscription"
  • name: The name of the method or subscription being called
  • name: 呼び出されるメソッドやsubscriptionの名前
  • userId: The user ID attempting the method or subscription
  • userId: メソッドやsubscriptionを呼び出そうとしているユーザID
  • connectionId: A string representing the user's DDP connection
  • connectionId: ユーザのDDPコネクションの文字列表現
  • clientAddress: The IP address of the user
  • clientAddress: ユーザのIPアドレス

Returns unique ruleId that can be passed to removeRule.

removeRuleに渡すことのできるユニークなruleIdを返す。

Arguments

matcher Object

Matchers specify which events are counted towards a rate limit. A matcher is an object that has a subset of the same properties as the event objects described above. Each value in a matcher object is one of the following:

matchersはどのイベントがレートリミットの対象となるか特定するものである。matcherはオブジェクトで、上記イベントオブジェクトのプロパティのサブセットとなる。matcherオブジェクトのそれぞれの値は次のいずれかである。:

  • a string: for the event to satisfy the matcher, this value must be equal to the value of the same property in the event object

    文字列: matcherに合うにはイベントオブジェクとは同じプロパティで同じ値を持つ必要がある。

  • a function: for the event to satisfy the matcher, the function must evaluate to true when passed the value of the same property in the event object

    関数: matcherに合うにはこの関数に同じプロパティの値を与えてtrueを返す必要がある。

Here's how events are counted: Each event that satisfies the matcher's filter is mapped to a bucket. Buckets are uniquely determined by the event object's values for all properties present in both the matcher and event objects.

イベントのカウント方法: それぞれのイベントがmatcherのフィルタに合うと1つのバケットに入る。バケットはイベントオブジェクトとmatcherに共通のプロパティのイベントオブジェクトの値で決まる。

numRequests number

number of requests allowed per time interval. Default = 10.

timeInterval毎に許可されるリクエスト数。デフォルトは10。

timeInterval number

time interval in milliseconds after which rule's counters are reset. Default = 1000.

カウンターがリセットされる時間間隔(ミリ秒)。デフォルトは1000。

Custom rules can be added by calling DDPRateLimiter.addRule. The rate limiter is called on every method and subscription invocation.

DDPRateLimiter.addRuleを呼び出すことで独自のルールを追加できます。レートリミットはメソッドやsubscriptionが実行されるたびに確認されます。

A rate limit is reached when a bucket has surpassed the rule's predefined capactiy, at which point errors will be returned for that input until the buckets are reset. Buckets are regularly reset after the end of a time interval.

ルールが定めた量をバケットが越えるとレートリミットが働き、バケットがリセットされるまでエラーが返されます。バケットはtimeIntervalが経過する毎にリセットされます。

Here's example of defining a rule and adding it into the DDPRateLimiter:

下記はルールを定義してDDPRateLimiterに追加する例です:

// Define a rule that matches login attempts by non-admin users
var loginRule = {
  userId: function (userId) {
    return Meteor.users.findOne(userId).type !== 'Admin';
  },
  type: 'method',
  name: 'login'
}
// Add the rule, allowing up to 5 messages every 1000 milliseconds.
DDPRateLimiter.addRule(loginRule, 5, 1000);

DDPRateLimiter.removeRule(id)

Removes the specified rule from the rate limiter. If rule had hit a rate limit, that limit is removed as well.

レートリミットからルールを削除する。ルールによってレートリミットの上限に到達している場合はその上限も削除される。

Arguments

id string

'ruleId' returned from addRule

'ruleId' addRuleから返されたもの

DDPRateLimiter.setErrorMessage(message)

Set error message text when method or subscription rate limit exceeded.

メソッドやsubscriptionのレートリミットが働いたときのエラーメッセージを指定する。

Arguments

message string or Function

Functions are passed in an object with a timeToReset field that specifies the number of milliseconds until the next method or subscription is allowed to run. The function must return a string of the error message.

関数を指定した場合は、timeToResetというプロパティを持つオブェクトが引数となり、メソッドやsubscriptionが次に許可されるまでの時間をミリ秒で渡される。関数は文字列を返す必要がある。

Check

The check package includes pattern checking functions useful for checking the types and structure of variables and an extensible library of patterns to specify which types you are expecting.

checkパッケージは、簡単に変数の型や構造をチェックすることができるパターンチェック関数と、 その型や構造を指定する拡張ライブラリを提供します。

Anywhere
check(value, pattern)

Check that a value matches a pattern. If the value does not match the pattern, throw a Match.Error.

値がパターンにマッチするかをチェックする。 もしパターンにマッチしない場合、Match.Errorをスローする。

Particularly useful to assert that arguments to a function have the right types and structure.

特に、関数の引数が正しい型や構造をしているか確認するのに役立つ。

Arguments

value Any

The value to check

確認する値

pattern Match Pattern

The pattern to match value against

valueに対するパターン

Meteor methods and publish functions take arbitrary EJSON types as arguments, but most arguments are expected to be of a particular type. check is a lightweight function for checking that arguments and other values are of the expected type. For example:

Meteorメソッドとpublish関数は任意のEJSON型を引数としてとるが、 多くの引数は特定の型を期待します。check は、関数の引数やその他の値をチェックするための軽量の関数です。 例えば:

Meteor.publish("chats-in-room", function (roomId) {
  // Make sure roomId is a string, not an arbitrary mongo selector object.
  check(roomId, String);
  return Chats.find({room: roomId});
});

Meteor.methods({addChat: function (roomId, message) {
  check(roomId, String);
  check(message, {
    text: String,
    timestamp: Date,
    // Optional, but if present must be an array of strings.
    tags: Match.Optional([String])
  });

  // ... do something with the message ...
}});

If the match fails, check throws a Match.Error describing how it failed. If this error gets sent over the wire to the client, it will appear only as Meteor.Error(400, "Match Failed"). The failure details will be written to the server logs but not revealed to the client.

マッチしない場合、checkは失敗の原因を記述したMatch.Errorの例外をスローします。もし このエラーがクライアント側に送られた場合、単に Meteor.Error(400, "Match Failed")となります。失敗の原因はサーバのログに書かれクライアントには開示されません。

Anywhere
Match.test(value, pattern)

Returns true if the value matches the pattern.

パターンにマッチした場合、trueを返す。

Arguments

value Any

The value to check

確認する値

pattern Match Pattern

The pattern to match value against

valueに対するパターン

Match.test can be used to identify if a variable has a certain structure.

Match.testは値の構造を判定するのに使います。

// will return true for {foo: 1, bar: "hello"} or similar
Match.test(value, {foo: Match.Integer, bar: String});

// will return true if value is a string
Match.test(value, String);

// will return true if value is a String or an array of Numbers
Match.test(value, Match.OneOf(String, [Number]));

This can be useful if you have a function that accepts several different kinds of objects, and you want to determine which was passed in.

これは、関数が複数の種類のオブジェクトを受け取る場合にどれが渡されたかを確認するのに使えます。

Match Patterns

The following patterns can be used as pattern arguments to check and Match.test:

下記は checkMatch.testの引数に使えるパターンです:

Match.Any

Matches any value.

任意の値にマッチします。

String, Number, Boolean, undefined, null

Matches a primitive of the given type.

与えられたプリミティブタイプにマッチします。

Match.Integer

Matches a signed 32-bit integer. Doesn't match Infinity, -Infinity, or NaN.

符号付32bit整数にマッチします。Infinity-InfinityNaNにはマッチしません。

[pattern]

A one-element array matches an array of elements, each of which match pattern. For example, [Number] matches a (possibly empty) array of numbers; [Match.Any] matches any array.

要素が一つの配列はすべての要素がpatternにマッチする配列にマッチします。例えば、[Number]は数値の配列(もしくは空の配列)にマッチします。また、[Match.Any]は任意の配列にマッチします。

{key1: pattern1, key2: pattern2, ...}

Matches an Object with the given keys, with values matching the given patterns. If any pattern is a Match.Optional, that key does not need to exist in the object. The value may not contain any keys not listed in the pattern. The value must be a plain Object with no special prototype.

与えられたキーとそのパターンのオブジェクトにマッチします。 もしpatternMatch.Optionalの場合、そのキーはオブジェクトに存在する必要がはありません。 対象の値はパターン載っていないキーを含むことはできません。 対象の値はプロトタイプを持たない単純なオブジェクトである必要があります。

Match.ObjectIncluding({key1: pattern1, key2: pattern2, ...})

Matches an Object with the given keys; the value may also have other keys with arbitrary values.

与えられたキーを含むオブジェクトにマッチします。対象の値は他の任意の値をもつキーを持つことができます。

Object

Matches any plain Object with any keys; equivalent to Match.ObjectIncluding({}).

与えられたキーを含むオブジェクトにマッチします。Match.ObjectIncluding({})と同等です。

Match.Optional(pattern)

Matches either undefined or something that matches pattern. If used in an object this matches only if the key is not set as opposed to the value being set to undefined.

undefinedもしくはパターンにマッチする何かにマッチします。もしオブジェクトの中で使われる場合は、キーが存在しない場合のみマッチし、値がundefinedの場合は該当しません。

// In an object
var pat = { name: Match.Optional(String) };
check({ name: "something" }, pat) // OK
check({}, pat) // OK
check({ name: undefined }, pat) // Throws an exception

// Outside an object
check(undefined, Match.Optional(String)); // OK
Match.OneOf(pattern1, pattern2, ...)

Matches any value that matches at least one of the provided patterns.

複数のパターンのいずれか一つにマッチする任意の値にマッチします。

Any constructor function (eg, Date)

Matches any element that is an instance of that type.

コンストラクタのインスタンスにマッチします。

Match.Where(condition)

Calls the function condition with the value as the argument. If condition returns true, this matches. If condition throws a Match.Error or returns false, this fails. If condition throws any other error, that error is thrown from the call to check or Match.test. Examples:

condition関数を対象の値を引数として呼び出し、もしtrueが返されればマッチします。もしcondition関数がMatch.Errorをスローしたりfalseを返す場合はマッチしません。もしcondition関数がそれ以外の例外をスローする場合はその例外がはcheckMatch.testにスローされます。例えば:

check(buffer, Match.Where(EJSON.isBinary));

NonEmptyString = Match.Where(function (x) {
  check(x, String);
  return x.length > 0;
});
check(arg, NonEmptyString);

Server connections

These functions manage and inspect the network connection between the Meteor client and server.

Client
Meteor.status()

Get the current connection status. A reactive data source.

This method returns the status of the connection between the client and the server. The return value is an object with the following fields:

connected Boolean

True if currently connected to the server. If false, changes and method invocations will be queued up until the connection is reestablished.

status String

Describes the current reconnection status. The possible values are connected (the connection is up and running), connecting (disconnected and trying to open a new connection), failed (permanently failed to connect; e.g., the client and server support different versions of DDP), waiting (failed to connect and waiting to try to reconnect) and offline (user has disconnected the connection).

retryCount Number

The number of times the client has tried to reconnect since the connection was lost. 0 when connected.

retryTime Number or undefined

The estimated time of the next reconnection attempt. To turn this into an interval until the next reconnection, use retryTime - (new Date()).getTime(). This key will be set only when status is waiting.

reason String or undefined

If status is failed, a description of why the connection failed.

Instead of using callbacks to notify you on changes, this is a reactive data source. You can use it in a template or computation to get realtime updates.

Client
Meteor.reconnect()

Force an immediate reconnection attempt if the client is not connected to the server.

This method does nothing if the client is already connected.

Client
Meteor.disconnect()

Disconnect the client from the server.

Call this method to disconnect from the server and stop all live data updates. While the client is disconnected it will not receive updates to collections, method calls will be queued until the connection is reestablished, and hot code push will be disabled.

Call Meteor.reconnect to reestablish the connection and resume data transfer.

This can be used to save battery on mobile devices when real time updates are not required.

Server
Meteor.onConnection(callback)

Register a callback to be called when a new DDP connection is made to the server.

Arguments

callback Function

The function to call when a new DDP connection is established.

onConnection returns an object with a single method stop. Calling stop unregisters the callback, so that this callback will no longer be called on new connections.

The callback is called with a single argument, the server-side connection representing the connection from the client. This object contains the following fields:

id String

A globally unique id for this connection.

close Function

Close this DDP connection. The client is free to reconnect, but will receive a different connection with a new id if it does.

onClose Function

Register a callback to be called when the connection is closed. If the connection is already closed, the callback will be called immediately.

clientAddress String

The IP address of the client in dotted form (such as "127.0.0.1").

If you're running your Meteor server behind a proxy (so that clients are connecting to the proxy instead of to your server directly), you'll need to set the HTTP_FORWARDED_COUNT environment variable for the correct IP address to be reported by clientAddress.

Set HTTP_FORWARDED_COUNT to an integer representing the number of proxies in front of your server. For example, you'd set it to "1" when your server was behind one proxy.

httpHeaders Object

When the connection came in over an HTTP transport (such as with Meteor's default SockJS implementation), this field contains whitelisted HTTP headers.

Cookies are deliberately excluded from the headers as they are a security risk for this transport. For details and alternatives, see the SockJS documentation.

Currently when a client reconnects to the server (such as after temporarily losing its Internet connection), it will get a new connection each time. The onConnection callbacks will be called again, and the new connection will have a new connection id.

In the future, when client reconnection is fully implemented, reconnecting from the client will reconnect to the same connection on the server: the onConnection callback won't be called for that connection again, and the connection will still have the same connection id.

Anywhere
DDP.connect(url)

Connect to the server of a different Meteor application to subscribe to its document sets and invoke its remote methods.

Arguments

url String

The URL of another Meteor application.

To call methods on another Meteor application or subscribe to its data sets, call DDP.connect with the URL of the application. DDP.connect returns an object which provides:

  • subscribe - Subscribe to a record set. See Meteor.subscribe.
  • call - Invoke a method. See Meteor.call.
  • apply - Invoke a method with an argument array. See Meteor.apply.
  • methods - Define client-only stubs for methods defined on the remote server. See Meteor.methods.
  • status - Get the current connection status. See Meteor.status.
  • reconnect - See Meteor.reconnect.
  • disconnect - See Meteor.disconnect.
  • onReconnect - Set this to a function to be called as the first step of reconnecting. This function can call methods which will be executed before any other outstanding methods. For example, this can be used to re-establish the appropriate authentication context on the new connection.

By default, clients open a connection to the server from which they're loaded. When you call Meteor.subscribe, Meteor.status, Meteor.call, and Meteor.apply, you are using a connection back to that default server.

Collections

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

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

コレクション名。もしnullを指定した場合、管理されない(同期されない)ローカルコレクションを作ります。

Options

connection Object

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

idGeneration String

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

The default id generation technique is 'STRING'.

transform Function

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

Calling this function is analogous to declaring a model in a traditional ORM (Object-Relation Mapper)-centric framework. It sets up a collection (a storage space for records, or "documents") that can be used to store a particular type of information, like users, posts, scores, todo items, or whatever matters to your application. Each document is a EJSON object. It includes an _id property whose value is unique in the collection, which Meteor will set when you first create the document.

// common code on client and server declares a DDP-managed mongo
// collection.
Chatrooms = new Mongo.Collection("chatrooms");
Messages = new Mongo.Collection("messages");

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

// return array of my messages
var myMessages = Messages.find({userId: Session.get('myUserId')}).fetch();

// create a new message
Messages.insert({text: "Hello, world!"});

// mark my first message as "important"
Messages.update(myMessages[0]._id, {$set: {important: true}});

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

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

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

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

  • When you write to the database on the client (insert, update, remove), the command is executed locally immediately, and, simultaneously, it's sent to the server and executed there too. This happens via stubs, because writes are implemented as methods.

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

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

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

meteor remove autopublish

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

// Create a collection called Posts and put a document in it. The
// document will be immediately visible in the local copy of the
// collection. It will be written to the server-side database
// a fraction of a second later, and a fraction of a second
// after that, it will be synchronized down to any other clients
// that are subscribed to a query that includes it (see
// Meteor.subscribe and autopublish)
Posts = new Mongo.Collection("posts");
Posts.insert({title: "Hello world", body: "First post"});

// Changes are visible immediately -- no waiting for a round trip to
// the server.
assert(Posts.find().count() === 1);

// Create a temporary, local collection. It works just like any other
// collection, but it doesn't send changes to the server, and it
// can't receive any data from subscriptions.
Scratchpad = new Mongo.Collection;
for (var i = 0; i < 10; i++)
  Scratchpad.insert({number: i * 2});
assert(Scratchpad.find({number: {$lt: 9}}).count() === 5);

Generally, you'll assign Mongo.Collection objects in your app to global variables. You can only create one Mongo.Collection object for each underlying Mongo collection.

If you specify a transform option to the Collection or any of its retrieval methods, documents are passed through the transform function before being returned or passed to callbacks. This allows you to add methods or otherwise modify the contents of your collection from their database representation. You can also specify transform on a particular find, findOne, allow, or deny call. Transform functions must return an object and they may not change the value of the document's _id field (though it's OK to leave it out).

// An Animal class that takes a document in its constructor
Animal = function (doc) {
  _.extend(this, doc);
};
_.extend(Animal.prototype, {
  makeNoise: function () {
    console.log(this.sound);
  }
});

// Define a Collection that uses Animal as its document
Animals = new Mongo.Collection("Animals", {
  transform: function (doc) { return new Animal(doc); }
});

// Create an Animal and call its makeNoise method
Animals.insert({name: "raptor", sound: "roar"});
Animals.findOne({name: "raptor"}).makeNoise(); // prints "roar"

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

In this release, Minimongo has some limitations:

  • $pull in modifiers can only accept certain kinds of selectors.
  • findAndModify, aggregate functions, and map/reduce aren't supported.

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

Minimongo doesn't currently have indexes. It's rare for this to be an issue, since it's unusual for a client to have enough data that an index is worthwhile.

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

Find the documents in a collection that match the selector.

コレクションの中から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.

取得する or 除外するフィールド

reactive Boolean

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

transform Function

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

find returns a cursor. It does not immediately access the database or return documents. Cursors provide fetch to return all matching documents, map and forEach to iterate over all matching documents, and observe and observeChanges to register callbacks when the set of matching documents changes.

Collection cursors are not query snapshots. If the database changes between calling Collection.find and fetching the results of the cursor, or while fetching results from the cursor, those changes may or may not appear in the result set.

Cursors are a reactive data source. On the client, the first time you retrieve a cursor's documents with fetch, map, or forEach inside a reactive computation (eg, a template or autorun), Meteor will register a dependency on the underlying data. Any change to the collection that changes the documents in a cursor will trigger a recomputation. To disable this behavior, pass {reactive: false} as an option to find.

Note that when fields are specified, only changes to the included fields will trigger callbacks in observe, observeChanges and invalidations in reactive computations using this cursor. Careful use of fields allows for more fine-grained reactivity for computations that don't depend on an entire document.

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

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

selectorにマッチする初めのドキュメントを検索します。sortやskipオプションで順序を指定できます。

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

結果の先頭からスキップする数

fields Mongo Field Specifier

Dictionary of fields to return or exclude.

取得する or 除外するフィールド

reactive Boolean

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

transform Function

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

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

Anywhere
collection.insert(doc, [callback])

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

コレクションにドキュメントを挿入します。そして一意の_idを返します。

Arguments

doc Object

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

挿入するドキュメント。_id属性が持っていない場合、Meteorは_idを生成します。

callback Function

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

オプション。存在した場合、コールバック関数の第1引数にエラーオブジェクトを渡します。もしエラーがなければ、_idを第2引数に渡します。

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

insert will generate a unique ID for the object you pass, insert it in the database, and return the ID. When insert is called from untrusted client code, it will be allowed only if passes any applicable allow and deny rules.

On the server, if you don't provide a callback, then insert blocks until the database acknowledges the write, or throws an exception if something went wrong. If you do provide a callback, insert still returns the ID immediately. Once the insert completes (or fails), the callback is called with error and result arguments. In an error case, result is undefined. If the insert is successful, error is undefined and result is the new document ID.

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

Example:

var groceriesId = Lists.insert({name: "Groceries"});
Items.insert({list: groceriesId, name: "Watercress"});
Items.insert({list: groceriesId, name: "Persimmons"});

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

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

コレクション内の1つまたは複数のドキュメントを修正します。影響を与えたドキュメントの数を返します。

Arguments

selector Mongo Selector, Object ID, or String

Specifies which documents to modify

修正したいドキュメントの指定します

modifier Mongo Modifier

Specifies how to modify the documents

ドキュメントをどのように修正するかを指定します

callback Function

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

オプション。存在する場合、コールバック関数の第1引数にエラーオブジェクトが渡されます。もしエラーがなければ、影響を与えたドキュメントの数を第2引数に渡します。

Options

multi Boolean

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

trueならselectorマッチするドキュメントをすべて修正します。falseならマッチするドキュメントの一つを修正します(デフォルト)。

upsert Boolean

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

trueならマッチするドキュメントが見つからなかった場合にドキュメントを新たに挿入します。

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

The behavior of update differs depending on whether it is called by trusted or untrusted code. Trusted code includes server code and method code. Untrusted code includes client-side code such as event handlers and a browser's JavaScript console.

  • Trusted code can modify multiple documents at once by setting multi to true, and can use an arbitrary Mongo selector to find the documents to modify. It bypasses any access control rules set up by allow and deny. The number of affected documents will be returned from the update call if you don't pass a callback.

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

On the server, if you don't provide a callback, then update blocks until the database acknowledges the write, or throws an exception if something went wrong. If you do provide a callback, update returns immediately. Once the update completes, the callback is called with a single error argument in the case of failure, or a second argument indicating the number of affected documents if the update was successful.

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

Client example:

// When the givePoints button in the admin dashboard is pressed,
// give 5 points to the current player. The new score will be
// immediately visible on everyone's screens.
Template.adminDashboard.events({
  'click .givePoints': function () {
    Players.update(Session.get("currentPlayer"), {$inc: {score: 5}});
  }
});

Server example:

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

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

Anywhere
collection.upsert(selector, modifier, [options], [callback])

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

Arguments

selector Mongo Selector, Object ID, or String

Specifies which documents to modify

修正したいドキュメントの指定します

modifier Mongo Modifier

Specifies how to modify the documents

ドキュメントをどのように修正するかを指定します

callback Function

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

オプション。存在する場合、コールバック関数の第1引数にエラーオブジェクトが渡されます。もしエラーがなければ、影響を与えたドキュメントの数を第2引数に渡します。

Options

multi Boolean

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

trueならselectorマッチするドキュメントをすべて修正します。falseならマッチするドキュメントの一つを修正します(デフォルト)。

Modify documents that match selector according to modifier, or insert a document if no documents were modified. upsert is the same as calling update with the upsert option set to true, except that the return value of upsert is an object that contain the keys numberAffected and insertedId. (update returns only the number of affected documents.)

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

オプション。もし存在する場合、引数にエラーオブジェクトが渡されたコールバック関数が呼ばれます。

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

The behavior of remove differs depending on whether it is called by trusted or untrusted code. Trusted code includes server code and method code. Untrusted code includes client-side code such as event handlers and a browser's JavaScript console.

  • Trusted code can use an arbitrary Mongo selector to find the documents to remove, and can remove more than one document at once by passing a selector that matches multiple documents. It bypasses any access control rules set up by allow and deny. The number of removed documents will be returned from remove if you don't pass a callback.

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

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

On the server, if you don't provide a callback, then remove blocks until the database acknowledges the write and then returns the number of removed documents, or throws an exception if something went wrong. If you do provide a callback, remove returns immediately. Once the remove completes, the callback is called with a single error argument in the case of failure, or a second argument indicating the number of removed documents if the remove was successful.

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

Client example:

// When the remove button is clicked on a chat message, delete
// that message.
Template.chat.events({
  'click .remove': function () {
    Messages.remove(this._id);
  }
});

Server example:

// When the server starts, clear the log, and delete all players
// with a karma of less than -2.
Meteor.startup(function () {
  if (Meteor.isServer) {
    Logs.remove({});
    Players.remove({karma: {$lt: -2}});
  }
});

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

データベースへの変更の提案を見て、許可すべきなら、trueを返す関数です。

fetch Array of Strings

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

transform Function

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

When a client calls insert, update, or remove on a collection, the collection's allow and deny callbacks are called on the server to determine if the write should be allowed. If at least one allow callback allows the write, and no deny callbacks deny the write, then the write is allowed to proceed.

These checks are run only when a client tries to write to the database directly, for example by calling update from inside an event handler. Server code is trusted and isn't subject to allow and deny restrictions. That includes methods that are called with Meteor.call — they are expected to do their own access checking rather than relying on allow and deny.

You can call allow as many times as you like, and each call can include any combination of insert, update, and remove functions. The functions should return true if they think the operation should be allowed. Otherwise they should return false, or nothing at all (undefined). In that case Meteor will continue searching through any other allow rules on the collection.

The available callbacks are:

insert(userId, doc)

The user userId wants to insert the document doc into the collection. Return true if this should be allowed.

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

update(userId, doc, fieldNames, modifier)

The user userId wants to update a document doc. (doc is the current version of the document from the database, without the proposed update.) Return true to permit the change.

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

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

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

remove(userId, doc)

The user userId wants to remove doc from the database. Return true to permit this.

When calling update or remove Meteor will by default fetch the entire document doc from the database. If you have large documents you may wish to fetch only the fields that are actually used by your functions. Accomplish this by setting fetch to an array of field names to retrieve.

Example:

// Create a collection where users can only modify documents that
// they own. Ownership is tracked by an 'owner' field on each
// document. All documents must be owned by the user that created
// them and ownership can't be changed. Only a document's owner
// is allowed to delete it, and the 'locked' attribute can be
// set on a document to prevent its accidental deletion.

Posts = new Mongo.Collection("posts");

Posts.allow({
  insert: function (userId, doc) {
    // the user must be logged in, and the document must be owned by the user
    return (userId && doc.owner === userId);
  },
  update: function (userId, doc, fields, modifier) {
    // can only change your own documents
    return doc.owner === userId;
  },
  remove: function (userId, doc) {
    // can only remove your own documents
    return doc.owner === userId;
  },
  fetch: ['owner']
});

Posts.deny({
  update: function (userId, doc, fields, modifier) {
    // can't change owners
    return _.contains(fields, 'owner');
  },
  remove: function (userId, doc) {
    // can't remove locked documents
    return doc.locked;
  },
  fetch: ['locked'] // no need to fetch 'owner'
});

If you never set up any allow rules on a collection then all client writes to the collection will be denied, and it will only be possible to write to the collection from server-side code. In this case you will have to create a method for each possible write that clients are allowed to do. You'll then call these methods with Meteor.call rather than having the clients call insert, update, and remove directly on the collection.

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

meteor remove insecure

Server
collection.deny(options)

Override allow rules.

allowルールを上書きします。

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.

データベースへの変更の提案を見て、拒否すべきなら、trueを返す関数です。allowルールで許可していても、denyルールで上書きされます

fetch Array of Strings

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

transform Function

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

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

When a client tries to write to a collection, the Meteor server first checks the collection's deny rules. If none of them return true then it checks the collection's allow rules. Meteor allows the write only if no deny rules return true and at least one allow rule returns true.

Server
collection.rawCollection()

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

Server
collection.rawDatabase()

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

Cursors

To create a cursor, use find. To access the documents in a cursor, use forEach, map, or fetch.

Anywhere
cursor.forEach(callback, [thisArg])

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

Arguments

callback Function

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

thisArg Any

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

This interface is compatible with Array.forEach.

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

Examples:

// Print the titles of the five top-scoring posts
var topPosts = Posts.find({}, {sort: {score: -1}, limit: 5});
var count = 0;
topPosts.forEach(function (post) {
  console.log("Title of post " + count + ": " + post.title);
  count += 1;
});

Anywhere
cursor.map(callback, [thisArg])

Map callback over all matching documents. Returns an Array.

Arguments

callback Function

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

thisArg Any

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

This interface is compatible with Array.map.

When called from a reactive computation, map registers dependencies on the matching documents.

On the server, if callback yields, other calls to callback may occur while the first call is waiting. If strict sequential execution is necessary, use forEach instead.

Anywhere
cursor.fetch()

Return all matching documents as an Array.

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

Anywhere
cursor.count()

Returns the number of documents that match a query.

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

Anywhere
cursor.observe(callbacks)

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

Arguments

callbacks Object

Functions to call to deliver the result set as it changes

Establishes a live query that invokes callbacks when the result of the query changes. The callbacks receive the entire contents of the document that was affected, as well as its old contents, if applicable. If you only need to receive the fields that changed, see observeChanges.

callbacks may have the following functions as properties:

added(document) or
addedAt(document, atIndex, before)

A new document document entered the result set. The new document appears at position atIndex. It is immediately before the document whose _id is before. before will be null if the new document is at the end of the results.

changed(newDocument, oldDocument) or
changedAt(newDocument, oldDocument, atIndex)

The contents of a document were previously oldDocument and are now newDocument. The position of the changed document is atIndex.

removed(oldDocument) or
removedAt(oldDocument, atIndex)

The document oldDocument is no longer in the result set. It used to be at position atIndex.

movedTo(document, fromIndex, toIndex, before)

A document changed its position in the result set, from fromIndex to toIndex (which is before the document with id before). Its current contents is document.

Use added, changed, and removed when you don't care about the order of the documents in the result set. They are more efficient than addedAt, changedAt, and removedAt.

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

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

Anywhere
cursor.observeChanges(callbacks)

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

Arguments

callbacks Object

Functions to call to deliver the result set as it changes

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

callbacks may have the following functions as properties:

added(id, fields) or
addedBefore(id, fields, before)

A new document entered the result set. It has the id and fields specified. fields contains all fields of the document excluding the _id field. The new document is before the document identified by before, or at the end if before is null.

changed(id, fields)

The document identified by id has changed. fields contains the changed fields with their new values. If a field was removed from the document then it will be present in fields with a value of undefined.

movedBefore(id, before)

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

removed(id)

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

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

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

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

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

Example:

// Keep track of how many administrators are online.
var count = 0;
var query = Users.find({admin: true, onlineNow: true});
var handle = query.observeChanges({
  added: function (id, user) {
    count++;
    console.log(user.name + " brings the total to " + count + " admins.");
  },
  removed: function () {
    count--;
    console.log("Lost one. We're now down to " + count + " admins.");
  }
});

// After five seconds, stop keeping the count.
setTimeout(function () {handle.stop();}, 5000);

Anywhere
new Mongo.ObjectID([hexString])

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

Arguments

hexString String

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

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

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

Mongo-Style Selectors

The simplest selectors are just a string or Mongo.ObjectID. These selectors match the document with that value in its _id field.

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

// Matches all documents where deleted is false
{deleted: false}

// Matches all documents where the name and cognomen are as given
{name: "Rhialto", cognomen: "the Marvelous"}

// Matches every document
{}

But they can also contain more complicated tests:

// Matches documents where age is greater than 18
{age: {$gt: 18}}

// Also matches documents where tags is an array containing "popular"
{tags: "popular"}

// Matches documents where fruit is one of three possibilities
{fruit: {$in: ["peach", "plum", "pear"]}}

See the complete documentation.

Mongo-Style Modifiers

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

// Set the 'admin' property on the document to true
{$set: {admin: true}}

// Add 2 to the 'votes' property, and add "Traz"
// to the end of the 'supporters' array
{$inc: {votes: 2}, $push: {supporters: "Traz"}}

But if a modifier doesn't contain any $-operators, then it is instead interpreted as a literal document, and completely replaces whatever was previously in the database. (Literal document modifiers are not currently supported by validated updates.)

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

See the full list of modifiers.

Sort Specifiers

Sorts may be specified using your choice of several syntaxes:

// All of these do the same thing (sort in ascending order by
// key "a", breaking ties in descending order of key "b")

[["a", "asc"], ["b", "desc"]]
["a", ["b", "desc"]]
{a: 1, b: -1}

The last form will only work if your JavaScript implementation preserves the order of keys in objects. Most do, most of the time, but it's up to you to be sure.

Field Specifiers

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

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

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

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

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

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

Field operators such as $ and $elemMatch are not available on the client side yet.

A more advanced example:

Users.insert({ alterEgos: [{ name: "Kira", alliance: "murderer" },
                           { name: "L", alliance: "police" }],
               name: "Yagami Light" });

Users.findOne({}, { fields: { 'alterEgos.name': 1, _id: 0 } });

// returns { alterEgos: [{ name: "Kira" }, { name: "L" }] }

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

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.

Session(セッション)はクライアント上のグローバルオブジェクトとして提供され、キーと値のペアのセットを格納するために使用できます。それは、リストで現在選択している項目のようなものを一時的に保持するのに使用します。

What's special about Session is that it's reactive. If you call Session.get("currentList") from inside a template, the template will automatically be rerendered whenever Session.set("currentList", x) is called.

Client
Session.set(key, value)

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

セッションに変数をセットします。また、リスナーに値が変更されたことが通知されます(例: Session.getでこのキーを呼び出しているテンプレートを再描画したり、Tracker.autorun処理を再実行します。

Arguments

key String

The key to set, eg, selectedItem

セッションのキー、例: selectedItem

value EJSON-able Object or undefined

The new value for key

keyの新しい値

Example:

Tracker.autorun(function () {
  Meteor.subscribe("chat-history", {room: Session.get("currentRoomId")});
});

// Causes the function passed to Tracker.autorun to be re-run, so
// that the chat-history subscription is moved to the room "home".
Session.set("currentRoomId", "home");

Session.set can also be called with an object of keys and values, which is equivalent to calling Session.set individually on each key/value pair.

Session.set({
  a: "foo",
  b: "bar"
});

Client
Session.setDefault(key, value)

Set a variable in the session if it hasn't been set before. Otherwise works exactly the same as Session.set.

Arguments

key String

The key to set, eg, selectedItem

セッションのキー、例: selectedItem

value EJSON-able Object or undefined

The new value for key

keyの新しい値

This is useful in initialization code, to avoid re-initializing a session variable every time a new version of your app is loaded.

Client
Session.get(key)

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.

セッション変数の値を取得します。もしリアクティブ処理の中では、Session.setにより変数の値が変更になった場合に処理が無効化(再計算)されます。これはセッション値のクローンを返します。そのため、それがオブジェクトまたは配列の場合、返された値を変更したとしても、セッションに格納されている値には影響を与えません。

Arguments

key String

The name of the session variable to return

値を取得したいセッション変数名

Example:

<!-- in main.html -->
<template name="main">
  <p>We've always been at war with {{theEnemy}}.</p>
</template>
// in main.js
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"

Client
Session.equals(key, value)

Test if a session variable is equal to a value. If inside a reactive computation, invalidate the computation the next time the variable changes to or from the value.

Arguments

key String

The name of the session variable to test

value String, Number, Boolean, null, or undefined

The value to test against

If value is a scalar, then these two expressions do the same thing:

(1) Session.get("key") === value
(2) Session.equals("key", value)

... but the second one is always better. It triggers fewer invalidations (template redraws), making your program more efficient.

Example:

<template name="postsView">
{{! Show a dynamically updating list of items. Let the user click on an
    item to select it. The selected item is given a CSS class so it
    can be rendered differently. }}

{{#each posts}}
  {{> postItem }}
{{/each}}
</template>

<template name="postItem">
  <div class="{{postClass}}">{{title}}</div>
</template>
// in JS file
Template.postsView.helpers({
  posts: function() {
    return Posts.find();
  }
});

Template.postItem.helpers({
  postClass: function() {
    return Session.equals("selectedPost", this._id) ?
      "selected" : "";
  }
});

Template.postItem.events({
  'click': function() {
    Session.set("selectedPost", this._id);
  }
});

Using Session.equals here means that when the user clicks on an item and changes the selection, only the newly selected and the newly unselected items are re-rendered.

If Session.get had been used instead of Session.equals, then when the selection changed, all the items would be re-rendered.

For object and array session values, you cannot use Session.equals; instead, you need to use the underscore package and write _.isEqual(Session.get(key), value).

Accounts

The Meteor Accounts system builds on top of the userId support in publish and methods. The core packages add the concept of user documents stored in the database, and additional packages add secure password authentication, integration with third party login services, and a pre-built user interface.

The basic Accounts system is in the accounts-base package, but applications typically include this automatically by adding one of the login provider packages: accounts-password, accounts-facebook, accounts-github, accounts-google, accounts-meetup, accounts-twitter, or accounts-weibo.

Anywhere but publish functions
Meteor.user()

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

現在ログイン中のユーザデータを返します。ログインしていない場合は、nullが返ります。これはリアクティブデータです。

Retrieves the user record for the current user from the Meteor.users collection.

On the client, this will be the subset of the fields in the document that are published from the server (other fields won't be available on the client). By default the server publishes username, emails, and profile (writable by user). See Meteor.users for more on the fields used in user documents.

Anywhere but publish functions
Meteor.userId()

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

現在ログイン中のユーザIDを返します。ログインしていない場合は、nullが返ります。これはリアクティブデータです。

Anywhere
Meteor.users

A Mongo.Collection containing user documents.

すべてのユーザデータを含むMongo.Collectionです。

This collection contains one document per registered user. Here's an example user document:

このコレクションは一人のユーザにつき一つのドキュメント(データ)を持ちます。下記がユーザドキュメントの一例です:

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

A user document can contain any data you want to store about a user. Meteor treats the following fields specially:

ユーザドキュメントには開発者が任意のデータを格納することができます。Meteorは下記のフィールドを特殊フィールドとして扱います。:

  • username: a unique String identifying the user.
  • username: ユーザを識別するユニークな文字列。
  • emails: an Array of Objects with keys address and verified; an email address may belong to at most one user. verified is a Boolean which is true if the user has verified the address with a token sent over email.
  • emails: オブジェクトの配列で、オブジェクトはaddressverifiedというプロパティを持つ。emailアドレスは一人のユーザに固有である必要がある。verifiedはBooleanで、ユーザがメールで遅られたトークンで認証してverified the addressとなった場合にtrueとなる。
  • createdAt: the Date at which the user document was created.
  • createdAt: ユーザドキュメントが作成された日時。
  • profile: an Object which the user can create and update with any data. Do not store anything on profile that you wouldn't want the user to edit unless you have a deny rule on the Meteor.users collection.
  • services: an Object containing data used by particular login services. For example, its reset field contains tokens used by forgot password links, and its resume field contains tokens used to keep you logged in between sessions.
  • services: 個別のログインサービスがデータを格納するオブジェクト。例えば、そのresetフィールドはforgot passwordのリンクで使われるトークンを保持する、また、resumeフィールドはセッションを横断してログイン状態を維持するためのトークンを保持する。

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

他のすべてのMongo.Collectionと同じように、サーバにおいてはすべてのドキュメントにアクセスできる。しかし、クライアントにおいては明示的にpublishされたものしかアクセスできない。

By default, the current user's username, emails and profile are published to the client. You can publish additional fields for the current user with:

デフォルトでは、現在のユーザのusernameemailsprofileはpublishされクライアントからアクセスできる。それ以外のフィールドを現在のユーザにpublishするには次のようにする:

// server
Meteor.publish("userData", function () {
  if (this.userId) {
    return Meteor.users.find({_id: this.userId},
                             {fields: {'other': 1, 'things': 1}});
  } else {
    this.ready();
  }
});

// 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 (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.

autopublishパッケージがインストールされている状態ではシステム上のすべてのユーザの情報がすべてのクライアントにpublishされる。これは、usernameprofileservices内の公開フィールド(例:services.facebook.idservices.twitter.screenName)が含まれる。これに加えて、autopublishパッケージを使った場合は、現在ログインしているユーザにはアクセストークンなどさらに情報がpublishされる。これにより、許可されていれば、クライアントからサービスに直接API呼び出しができるようになる。

Users are by default allowed to specify their own profile field with Accounts.createUser and 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:

デフォルトではユーザは自分でprofileフィールドを設定したり修正したりするこができる。設定はAccounts.createUserを使い、修正はMeteor.users.updateを使う。ユーザに他のフィールドも追加で編集させるには、Meteor.users.allowを使う。逆にユーザにドキュメントをまったく修正させないようにするには、次のようにする:

Meteor.users.deny({update: function () { return true; }});

Client
Meteor.loggingIn()

True if a login method (such as Meteor.loginWithPassword, Meteor.loginWithFacebook, or Accounts.createUser) is currently in progress. A reactive data source.

For example, the accounts-ui package uses this to display an animation while the login request is being processed.

Client
Meteor.logout([callback])

Log the user out.

Arguments

callback Function

Optional callback. Called with no arguments on success, or with a single Error argument on failure.

Client
Meteor.logoutOtherClients([callback])

Log out other clients logged in as the current user, but does not log out the client that calls this function.

Arguments

callback Function

Optional callback. Called with no arguments on success, or with a single Error argument on failure.

For example, when called in a user's browser, connections in that browser remain logged in, but any other browsers or DDP clients logged in as that user will be logged out.

Client
Meteor.loginWithPassword(user, password, [callback])

Log the user in with a password.

Arguments

user Object or String

Either a string interpreted as a username or an email; or an object with a single key: email, username or id. Username or email match in a case insensitive manner.

password String

The user's password.

callback Function

Optional callback. Called with no arguments on success, or with a single Error argument on failure.

If there are multiple users with a username or email only differing in case, a case sensitive match is required. Although createUser won't let you create users with ambiguous usernames or emails, this could happen with existing databases or if you modify the users collection directly.

This function is provided by the accounts-password package. See the Passwords section below.

Client
Meteor.loginWith<ExternalService>([options], [callback])

Log the user in using an external service.

Arguments

callback Function

Optional callback. Called with no arguments on success, or with a single Error argument on failure. The callback cannot be called if you are using the "redirect" loginStyle, because the app will have reloaded in the meantime; try using client-side login hooks instead.

Options

requestPermissions Array of Strings

A list of permissions to request from the user.

requestOfflineToken Boolean

If true, asks the user for permission to act on their behalf when offline. This stores an additional offline token in the services field of the user document. Currently only supported with Google.

loginUrlParameters Object

Provide additional parameters to the authentication uri. Currently only supported with Google {@url https://developers.google.com/identity/protocols/OpenIDConnect#authenticationuriparameters}.

loginHint String

An email address that the external service will use to pre-fill the login prompt. Currently only supported with Meteor developer accounts and Google accounts. If used with Google, the Google User ID can also be passed.

loginStyle String

Login style ("popup" or "redirect", defaults to the login service configuration). The "popup" style opens the login page in a separate popup window, which is generally preferred because the Meteor application doesn't need to be reloaded. The "redirect" style redirects the Meteor application's window to the login page, and the login service provider redirects back to the Meteor application which is then reloaded. The "redirect" style can be used in situations where a popup window can't be opened, such as in a mobile UIWebView. The "redirect" style however relies on session storage which isn't available in Safari private mode, so the "popup" style will be forced if session storage can't be used.

redirectUrl String

If using "redirect" login style, the user will be returned to this URL after authorisation has been completed.

Available functions are:

  • Meteor.loginWithMeteorDeveloperAccount
  • Meteor.loginWithFacebook
  • Meteor.loginWithGithub
  • Meteor.loginWithGoogle
  • Meteor.loginWithMeetup
  • Meteor.loginWithTwitter
  • Meteor.loginWithWeibo

These functions initiate the login process with an external service (eg: Facebook, Google, etc), using OAuth. When called they open a new pop-up window that loads the provider's login page. Once the user has logged in with the provider, the pop-up window is closed and the Meteor client logs in to the Meteor server with the information provided by the external service.

In addition to identifying the user to your application, some services have APIs that allow you to take action on behalf of the user. To request specific permissions from the user, pass the requestPermissions option the login function. This will cause the user to be presented with an additional page in the pop-up dialog to permit access to their data. The user's accessToken — with permissions to access the service's API — is stored in the services field of the user document. The supported values for requestPermissions differ for each login service and are documented on their respective developer sites:

External login services typically require registering and configuring your application before use. The easiest way to do this is with the accounts-ui package which presents a step-by-step guide to configuring each service. However, the data can be also be entered manually in the ServiceConfiguration.configurations collection, which is exported by the service-configuration package.

First, add the service configuration package:

meteor add service-configuration

Then, in your app:

ServiceConfiguration.configurations.upsert(
  { service: "weibo" },
  {
    $set: {
      clientId: "1292962797",
      loginStyle: "popup",
      secret: "75a730b58f5691de5522789070c319bc"
    }
  }
);

Each external service has its own login provider package and login function. For example, to support GitHub login, run in your terminal:

meteor add accounts-github

and use the Meteor.loginWithGithub function:

Meteor.loginWithGithub({
  requestPermissions: ['user', 'public_repo']
}, function (err) {
  if (err)
    Session.set('errorMessage', err.reason || 'Unknown error');
});

Login service configuration is sent from the server to the client over DDP when your app starts up; you may not call the login function until the configuration is loaded. The function Accounts.loginServicesConfigured() is a reactive data source that will return true once the login service is configured; you should not make login buttons visible or active until it is true.

Ensure that your $ROOT_URL matches the authorized domain and callback URL that you configure with the external service (for instance, if you are running Meteor behind a proxy server, $ROOT_URL should be the externally-accessible URL, not the URL inside your proxy).

{{ currentUser }}

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

Meteor.user()を呼び出す。ユーザがログインしていがかだけをチェックする場合は、{{#if currentUser}}を使う。

Client
Accounts.ui.config(options)

Configure the behavior of {{> loginButtons}}.

Options

requestPermissions Object

Which permissions to request from the user for each external service.

requestOfflineToken Object

To ask the user for permission to act on their behalf when offline, map the relevant external service to true. Currently only supported with Google. See Meteor.loginWithExternalService for more details.

forceApprovalPrompt Object

If true, forces the user to approve the app's permissions, even if previously approved. Currently only supported with Google.

passwordSignupFields String

Which fields to display in the user creation form. One of 'USERNAME_AND_EMAIL', 'USERNAME_AND_OPTIONAL_EMAIL', 'USERNAME_ONLY', or 'EMAIL_ONLY' (default).

Example:

Accounts.ui.config({
  requestPermissions: {
    facebook: ['user_likes'],
    github: ['user', 'repo']
  },
  requestOfflineToken: {
    google: true
  },
  passwordSignupFields: 'USERNAME_AND_OPTIONAL_EMAIL'
});

Accounts (multi-server)

The accounts-base package exports two constructors, called AccountsClient and AccountsServer, which are used to create the Accounts object that is available on the client and the server, respectively.

This predefined Accounts object (along with similar convenience methods of Meteor, such as Meteor.logout) is sufficient to implement most accounts-related logic in Meteor apps. Nevertheless, these two constructors can be instantiated more than once, to create multiple independent connections between different accounts servers and their clients, in more complicated authentication situations.

Client
new AccountsClient(options)

Constructor for the Accounts object on the client.

Options

connection Object

Optional DDP connection to reuse.

ddpUrl String

Optional URL for creating a new DDP connection.

At most one of options.connection and options.ddpUrl should be provided in any instantiation of AccountsClient. If neither is provided, Meteor.connection will be used as the .connection property of the AccountsClient instance.

Note that AccountsClient is currently available only on the client, due to its use of browser APIs such as window.localStorage. In principle, though, it might make sense to establish a client connection from one server to another remote accounts server. Please let us know if you find yourself needing this server-to-server functionality.

Server
new AccountsServer(server)

Constructor for the Accounts namespace on the server.

Arguments

server Object

A server object such as Meteor.server.

The AccountsClient and AccountsServer classes share a common superclass, AccountsCommon. Methods defined on AccountsCommon.prototype will be available on both the client and the server, via the predefined Accounts object (most common) or any custom accountsClientOrServer object created using the AccountsClient or AccountsServer constructors (less common).

Here are a few of those methods:

Anywhere but publish functions
accountsClientOrServer.userId()

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

現在ログイン中のユーザIDを返します。ログインしていない場合は、nullが返ります。これはリアクティブデータです。

Anywhere but publish functions
accountsClientOrServer.user()

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

現在ログイン中のユーザデータを返します。ログインしていない場合は、nullが返ります。これはリアクティブデータです。

Anywhere
accountsClientOrServer.config(options)

Set global accounts options.

Options

sendVerificationEmail Boolean

New users with an email address will receive an address verification email.

forbidClientAccountCreation Boolean

Calls to createUser from the client will be rejected. In addition, if you are using accounts-ui, the "Create account" link will not be available.

restrictCreationByEmailDomain String or Function

If set to a string, only allows new users if the domain part of their email address matches the string. If set to a function, only allows new users if the function returns true. The function is passed the full email address of the proposed new user. Works with password-based sign-in and external services that expose email addresses (Google, Facebook, GitHub). All existing users still can log in after enabling this option. Example: Accounts.config({ restrictCreationByEmailDomain: 'school.edu' }).

loginExpirationInDays Number

The number of days from when a user logs in until their token expires and they are logged out. Defaults to 90. Set to null to disable login expiration.

oauthSecretKey String

When using the oauth-encryption package, the 16 byte key using to encrypt sensitive account credentials in the database, encoded in base64. This option may only be specifed on the server. See packages/oauth-encryption/README.md for details.

These methods are defined on AccountsClient.prototype, and are thus available only on the client:

Client
accountsClient.loggingIn()

True if a login method (such as Meteor.loginWithPassword, Meteor.loginWithFacebook, or Accounts.createUser) is currently in progress. A reactive data source.

Client
accountsClient.logout([callback])

Log the user out.

Arguments

callback Function

Optional callback. Called with no arguments on success, or with a single Error argument on failure.

Client
accountsClient.logoutOtherClients([callback])

Log out other clients logged in as the current user, but does not log out the client that calls this function.

Arguments

callback Function

Optional callback. Called with no arguments on success, or with a single Error argument on failure.

These methods are defined on AccountsServer.prototype, and are thus available only on the server:

Server
accountsServer.validateNewUser(func)

Set restrictions on new user creation.

Arguments

func Function

Called whenever a new user is created. Takes the new user object, and returns true to allow the creation or false to abort.

This can be called multiple times. If any of the functions return false or throw an error, the new user creation is aborted. To set a specific error message (which will be displayed by accounts-ui), throw a new Meteor.Error.

Example:

// Validate username, sending a specific error message on failure.
Accounts.validateNewUser(function (user) {
  if (user.username && user.username.length >= 3)
    return true;
  throw new Meteor.Error(403, "Username must have at least 3 characters");
});
// Validate username, without a specific error message.
Accounts.validateNewUser(function (user) {
  return user.username !== "root";
});

If the user is being created as part of a login attempt from a client (eg, calling Accounts.createUser from the client, or logging in for the first time with an external service), these callbacks are called before the Accounts.validateLoginAttempt callbacks. If these callbacks succeed but those fail, the user will still be created but the connection will not be logged in as that user.

Server
accountsServer.onCreateUser(func)

Customize new user creation.

Arguments

func Function

Called whenever a new user is created. Return the new user object, or throw an Error to abort the creation.

Use this when you need to do more than simply accept or reject new user creation. With this function you can programatically control the contents of new user documents.

The function you pass will be called with two arguments: options and user. The options argument comes from Accounts.createUser for password-based users or from an external service login flow. options may come from an untrusted client so make sure to validate any values you read from it. The user argument is created on the server and contains a proposed user object with all the automatically generated fields required for the user to log in, including the _id.

The function should return the user document (either the one passed in or a newly-created object) with whatever modifications are desired. The returned document is inserted directly into the Meteor.users collection.

The default create user function simply copies options.profile into the new user document. Calling onCreateUser overrides the default hook. This can only be called once.

Example:

// Support for playing D&D: Roll 3d6 for dexterity
Accounts.onCreateUser(function(options, user) {
  var d6 = function () { return Math.floor(Random.fraction() * 6) + 1; };
  user.dexterity = d6() + d6() + d6();
  // We still want the default hook's 'profile' behavior.
  if (options.profile)
    user.profile = options.profile;
  return user;
});

Server
accountsServer.validateLoginAttempt(func)

Validate login attempts.

Arguments

func Function

Called whenever a login is attempted (either successful or unsuccessful). A login can be aborted by returning a falsy value or throwing an exception.

Call validateLoginAttempt with a callback to be called on login attempts. It returns an object with a single method, stop. Calling stop() unregisters the callback.

When a login attempt is made, the registered validate login callbacks are called with a single argument, the attempt info object:

type String

The service name, such as "password" or "twitter".

allowed Boolean

Whether this login is allowed and will be successful (if not aborted by any of the validateLoginAttempt callbacks). False if the login will not succeed (for example, an invalid password or the login was aborted by a previous validateLoginAttempt callback).

error Exception

When allowed is false, the exception describing why the login failed. It will be a Meteor.Error for failures reported to the user (such as invalid password), and can be a another kind of exception for internal errors.

user Object

When it is known which user was attempting to login, the Meteor user object. This will always be present for successful logins.

connection Object

The connection object the request came in on. See Meteor.onConnection for details.

methodName String

The name of the Meteor method being used to login.

methodArguments Array

An array of the arguments passed to the login method.

A validate login callback must return a truthy value for the login to proceed. If the callback returns a falsy value or throws an exception, the login is aborted. Throwing a Meteor.Error will report the error reason to the user.

All registered validate login callbacks are called, even if one of the callbacks aborts the login. The later callbacks will see the allowed field set to false since the login will now not be successful. This allows later callbacks to override an error from a previous callback; for example, you could override the "Incorrect password" error with a different message.

Validate login callbacks that aren't explicitly trying to override a previous error generally have no need to run if the attempt has already been determined to fail, and should start with

if (!attempt.allowed)
  return false;

Anywhere
accountsClientOrServer.onLogin(func)

Register a callback to be called after a login attempt succeeds.

Arguments

func Function

The callback to be called when login is successful.

See description of AccountsCommon#onLoginFailure for details.

Anywhere
accountsClientOrServer.onLoginFailure(func)

Register a callback to be called after a login attempt fails.

Arguments

func Function

The callback to be called after the login has failed.

Either the onLogin or the onLoginFailure callbacks will be called for each login attempt. The onLogin callbacks are called after the user has been successfully logged in. The onLoginFailure callbacks are called after a login attempt is denied.

These functions return an object with a single method, stop. Calling stop() unregisters the callback.

On the server, the callbacks get a single argument, the same attempt info object as validateLoginAttempt. On the client, no arguments are passed.

Rate Limiting

By default, there are rules added to the DDPRateLimiter that rate limit logins, new user registration and password reset calls to a limit of 5 requests per 10 seconds per session. These are a basic solution to dictionary attacks where a malicious user attempts to guess the passwords of legitimate users by attempting all possible passwords.

These rate limiting rules can be removed by calling Accounts.removeDefaultRateLimit(). Please see the DDPRateLimiter docs for more information.

Passwords

The accounts-password package contains a full system for password-based authentication. In addition to the basic username and password-based sign-in process, it also supports email-based sign-in including address verification and password recovery emails.

The Meteor server stores passwords using the bcrypt algorithm. This helps protect against embarrassing password leaks if the server's database is compromised.

To add password support to your application, run this command in your terminal:

meteor add accounts-password

You can construct your own user interface using the functions below, or use the accounts-ui package to include a turn-key user interface for password-based sign-in.

Anywhere
Accounts.createUser(options, [callback])

Create a new user.

Arguments

callback Function

Client only, optional callback. Called with no arguments on success, or with a single Error argument on failure.

Options

username String

A unique name for this user.

email String

The user's email address.

password String

The user's password. This is not sent in plain text over the wire.

profile Object

The user's profile, typically including the name field.

On the client, this function logs in as the newly created user on successful completion. On the server, it returns the newly created user id.

On the client, you must pass password and at least one of username or email — enough information for the user to be able to log in again later. If there are existing users with a username or email only differing in case, createUser will fail. On the server, you do not need to specify password, but the user will not be able to log in until it has a password (eg, set with Accounts.setPassword).

To create an account without a password on the server and still let the user pick their own password, call createUser with the email option and then call Accounts.sendEnrollmentEmail. This will send the user an email with a link to set their initial password.

By default the profile option is added directly to the new user document. To override this behavior, use Accounts.onCreateUser.

This function is only used for creating users with passwords. The external service login flows do not use this function.

Managing usernames and emails

Instead of modifying documents in the Meteor.users collection directly, use these convenience functions which correctly check for case insensitive duplicates before updates.

Server
Accounts.setUsername(userId, newUsername)

Change a user's username. Use this instead of updating the database directly. The operation will fail if there is an existing user with a username only differing in case.

Arguments

userId String

The ID of the user to update.

newUsername String

A new username for the user.

Server
Accounts.addEmail(userId, newEmail, [verified])

Add an email address for a user. Use this instead of directly updating the database. The operation will fail if there is a different user with an email only differing in case. If the specified user has an existing email only differing in case however, we replace it.

Arguments

userId String

The ID of the user to update.

newEmail String

A new email address for the user.

verified Boolean

Optional - whether the new email address should be marked as verified. Defaults to false.

By default, an email address is added with { verified: false }. Use Accounts.sendVerificationEmail to send an email with a link the user can use verify their email address.

Server
Accounts.removeEmail(userId, email)

Remove an email address for a user. Use this instead of updating the database directly.

Arguments

userId String

The ID of the user to update.

email String

The email address to remove.

Client
Accounts.verifyEmail(token, [callback])

Marks the user's email address as verified. Logs the user in afterwards.

Arguments

token String

The token retrieved from the verification URL.

callback Function

Optional callback. Called with no arguments on success, or with a single Error argument on failure.

This function accepts tokens passed into the callback registered with Accounts.onEmailVerificationLink.

Server
Accounts.findUserByUsername(username)

Finds the user with the specified username. First tries to match username case sensitively; if that fails, it tries case insensitively; but if more than one user matches the case insensitive search, it returns null.

Arguments

username String

The username to look for

Server
Accounts.findUserByEmail(email)

Finds the user with the specified email. First tries to match email case sensitively; if that fails, it tries case insensitively; but if more than one user matches the case insensitive search, it returns null.

Arguments

email String

The email address to look for

Managing passwords

Use the below functions to initiate password changes or resets from the server or the client.

Client
Accounts.changePassword(oldPassword, newPassword, [callback])

Change the current user's password. Must be logged in.

Arguments

oldPassword String

The user's current password. This is not sent in plain text over the wire.

newPassword String

A new password for the user. This is not sent in plain text over the wire.

callback Function

Optional callback. Called with no arguments on success, or with a single Error argument on failure.

Client
Accounts.forgotPassword(options, [callback])

Request a forgot password email.

Arguments

callback Function

Optional callback. Called with no arguments on success, or with a single Error argument on failure.

Options

email String

The email address to send a password reset link.

This triggers a call to Accounts.sendResetPasswordEmail on the server. When the user visits the link in this email, the callback registered with Accounts.onResetPasswordLink will be called.

If you are using the accounts-ui package, this is handled automatically. Otherwise, it is your responsiblity to prompt the user for the new password and call resetPassword.

Client
Accounts.resetPassword(token, newPassword, [callback])

Reset the password for a user using a token received in email. Logs the user in afterwards.

Arguments

token String

The token retrieved from the reset password URL.

newPassword String

A new password for the user. This is not sent in plain text over the wire.

callback Function

Optional callback. Called with no arguments on success, or with a single Error argument on failure.

This function accepts tokens passed into the callbacks registered with AccountsClient#onResetPasswordLink and Accounts.onEnrollmentLink.

Server
Accounts.setPassword(userId, newPassword, [options])

Forcibly change the password for a user.

Arguments

userId String

The id of the user to update.

newPassword String

A new password for the user.

Options

logout Object

Logout all current connections with this userId (default: true)

Sending emails

Server
Accounts.sendResetPasswordEmail(userId, [email])

Send an email with a link the user can use to reset their password.

Arguments

userId String

The id of the user to send email to.

email String

Optional. Which address of the user's to send the email to. This address must be in the user's emails list. Defaults to the first email in the list.

When the user visits the link in this email, the callback registered with AccountsClient#onResetPasswordLink will be called.

To customize the contents of the email, see Accounts.emailTemplates.

Server
Accounts.sendEnrollmentEmail(userId, [email])

Send an email with a link the user can use to set their initial password.

Arguments

userId String

The id of the user to send email to.

email String

Optional. Which address of the user's to send the email to. This address must be in the user's emails list. Defaults to the first email in the list.

When the user visits the link in this email, the callback registered with Accounts.onEnrollmentLink will be called.

To customize the contents of the email, see Accounts.emailTemplates.

Server
Accounts.sendVerificationEmail(userId, [email])

Send an email with a link the user can use verify their email address.

Arguments

userId String

The id of the user to send email to.

email String

Optional. Which address of the user's to send the email to. This address must be in the user's emails list. Defaults to the first unverified email in the list.

When the user visits the link in this email, the callback registered with Accounts.onEmailVerificationLink will be called.

To customize the contents of the email, see Accounts.emailTemplates.

Register a function to call when a reset password link is clicked in an email sent by Accounts.sendResetPasswordEmail. This function should be called in top-level code, not inside Meteor.startup().

Arguments

callback Function

The function to call. It is given two arguments:

  1. token: A password reset token that can be passed to Accounts.resetPassword.
  2. done: A function to call when the password reset UI flow is complete. The normal login process is suspended until this function is called, so that the password for user A can be reset even if user B was logged in.

Register a function to call when an account enrollment link is clicked in an email sent by Accounts.sendEnrollmentEmail. This function should be called in top-level code, not inside Meteor.startup().

Arguments

callback Function

The function to call. It is given two arguments:

  1. token: A password reset token that can be passed to Accounts.resetPassword to give the newly enrolled account a password.
  2. done: A function to call when the enrollment UI flow is complete. The normal login process is suspended until this function is called, so that user A can be enrolled even if user B was logged in.

Register a function to call when an email verification link is clicked in an email sent by Accounts.sendVerificationEmail. This function should be called in top-level code, not inside Meteor.startup().

Arguments

callback Function

The function to call. It is given two arguments:

  1. token: An email verification token that can be passed to Accounts.verifyEmail.
  2. done: A function to call when the email verification UI flow is complete. The normal login process is suspended until this function is called, so that the user can be notified that they are verifying their email before being logged in.

Server
Accounts.emailTemplates

Options to customize emails sent from the Accounts system.

This is an Object with several fields that are used to generate text/html for the emails sent by sendResetPasswordEmail, sendEnrollmentEmail, and sendVerificationEmail.

Override fields of the object by assigning to them:

  • from: A String with an RFC5322 From address. By default, the email is sent from no-reply@meteor.com. If you wish to receive email from users asking for help with their account, be sure to set this to an email address that you can receive email at.
  • siteName: The public name of your application. Defaults to the DNS name of the application (eg: awesome.meteor.com).
  • headers: An Object for custom email headers as described in Email.send.
  • resetPassword: An Object with the fields:
    • from: A Function used to override the from address defined by the emailTemplates.from field.
    • subject: A Function that takes a user object and returns a String for the subject line of a reset password email.
    • text: An optional Function that takes a user object and a url, and returns the body text for a reset password email.
    • html: An optional Function that takes a user object and a url, and returns the body html for a reset password email.
  • enrollAccount: Same as resetPassword, but for initial password setup for new accounts.
  • verifyEmail: Same as resetPassword, but for verifying the users email address.

Example:

Accounts.emailTemplates.siteName = "AwesomeSite";
Accounts.emailTemplates.from = "AwesomeSite Admin <accounts@example.com>";
Accounts.emailTemplates.enrollAccount.subject = function (user) {
    return "Welcome to Awesome Town, " + user.profile.name;
};
Accounts.emailTemplates.enrollAccount.text = function (user, url) {
   return "You have been selected to participate in building a better future!"
     + " To activate your account, simply click the link below:\n\n"
     + url;
};

Templates

When you write a template as <template name="foo"> ... </template> in an HTML file in your app, Meteor generates a "template object" named Template.foo. Note that template name cannot contain hyphens and other special characters.

The same template may occur many times on a page, and these occurrences are called template instances. Template instances have a life cycle of being created, put into the document, and later taken out of the document and destroyed. Meteor manages these stages for you, including determining when a template instance has been removed or replaced and should be cleaned up. You can associate data with a template instance, and you can access its DOM nodes when it is in the document.

Client
Template.myTemplate.events(eventMap)

Specify event handlers for this template.

テンプレートのイベントハンドラを指定する

Arguments

eventMap Event Map

Event handlers to associate with this template.

テンプレートに関係づけるイベントハンドラ

Declare event handlers for instances of this template. Multiple calls add new event handlers in addition to the existing ones.

See Event Maps for a detailed description of the event map format and how event handling works in Meteor.

Client
Template.myTemplate.helpers(helpers)

Specify template helpers available to this template.

このテンプレート用のテンプレートヘルパーを指定する。

Arguments

helpers Object

Dictionary of helper functions by name.

名前とヘルパー関数の辞書

Each template has a local dictionary of helpers that are made available to it, and this call specifies helpers to add to the template's dictionary.

Example:

Template.myTemplate.helpers({
  foo: function () {
    return Session.get("foo");
  }
});

Now you can invoke this helper with {{foo}} in the template defined with <template name="myTemplate">.

Helpers can accept positional and keyword arguments:

Template.myTemplate.helpers({
  displayName: function (firstName, lastName, keyword) {
    var prefix = keyword.hash.title ? keyword.hash.title + " " : "";
    return prefix + firstName + " " + lastName;
  }
});

Then you can call this helper from template like this:

{{displayName "John" "Doe" title="President"}}

You can learn more about arguments to helpers in Spacebars Readme.

Under the hood, each helper starts a new Tracker.autorun. When its reactive dependencies change, the helper is rerun. Helpers depend on their data context, passed arguments and other reactive data sources accessed during execution.

To create a helper that can be used in any template, use Template.registerHelper.

Client
Template.myTemplate.onRendered

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

テンプレートがDOMに追加されたときに呼び出される関数を登録する。

Arguments

callback Function

A function to be added as a callback.

コールバック関数

Callbacks added with this method are called once when an instance of Template.myTemplate is rendered into DOM nodes and put into the document for the first time.

In the body of a callback, this is a template instance object that is unique to this occurrence of the template and persists across re-renderings. Use the onCreated and onDestroyed callbacks to perform initialization or clean-up on the object.

Because your template has been rendered, you can use functions like this.findAll which look at its DOM nodes.

This can be a good place to apply any DOM manipulations you want, after the template is rendered for the first time.

<template name="myPictures">
  <div class="container">
    
  </div>
</template>
Template.myPictures.onRendered(function () {
  // Use the Packery jQuery plugin
  this.$('.container').packery({
    itemSelector: '.item',
    gutter: 10
  });
});

Client
Template.myTemplate.onCreated

Register a function to be called when an instance of this template is created.

Arguments

callback Function

A function to be added as a callback.

コールバック関数

Callbacks added with this method are called before your template's logic is evaluated for the first time. Inside a callback, this is the new template instance object. Properties you set on this object will be visible from the callbacks added with onRendered and onDestroyed methods and from event handlers.

These callbacks fire once and are the first group of callbacks to fire. Handling the created event is a useful way to set up values on template instance that are read from template helpers using Template.instance().

Template.myPictures.onCreated(function () {
  // set up local reactive variables
  this.highlightedPicture = new ReactiveVar(null);

  // register this template within some central store
  GalleryTemplates.push(this);
});

Client
Template.myTemplate.onDestroyed

Register a function to be called when an instance of this template is removed from the DOM and destroyed.

Arguments

callback Function

A function to be added as a callback.

コールバック関数

These callbacks are called when an occurrence of a template is taken off the page for any reason and not replaced with a re-rendering. Inside a callback, this is the template instance object being destroyed.

This group of callbacks is most useful for cleaning up or undoing any external effects of created or rendered groups. This group fires once and is the last callback to fire.

Template.myPictures.onDestroyed(function () {
  // deregister from some central store
  GalleryTemplates = _.without(GalleryTemplates, this);
});

Template instances

A template instance object represents an occurrence of a template in the document. It can be used to access the DOM and it can be assigned properties that persist as the template is reactively updated.

Template instance objects are found as the value of this in the onCreated, onRendered, and onDestroyed template callbacks, and as an argument to event handlers. You can access the current template instance from helpers using Template.instance().

In addition to the properties and functions described below, you can assign additional properties of your choice to the object. Use the onCreated and onDestroyed methods to add callbacks performing initialization or clean-up on the object.

You can only access findAll, find, firstNode, and lastNode from the onRendered callback and event handlers, not from onCreated and onDestroyed, because they require the template instance to be in the DOM.

Template instance objects are instanceof Blaze.TemplateInstance.

Client
template.findAll(selector)

Find all elements matching selector in this template instance.

テンプレート内でselectorにマッチする要素をすべて見つける

Arguments

selector String

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

マッチするCSSセレクタ。テンプレート内に限定される。

template.findAll returns an array of DOM elements matching selector.

Client
template.$(selector)

Find all elements matching selector in this template instance, and return them as a JQuery object.

Arguments

selector String

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

マッチするCSSセレクタ。テンプレート内に限定される。

template.$ returns a jQuery object of those same elements. jQuery objects are similar to arrays, with additional methods defined by the jQuery library.

The template instance serves as the document root for the selector. Only elements inside the template and its sub-templates can match parts of the selector.

Client
template.find(selector)

Find one element matching selector in this template instance.

テンプレート内でselectorにマッチする要素をひとつ見つける

Arguments

selector String

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

マッチするCSSセレクタ。テンプレート内に限定される。

Returns one DOM element matching selector, or null if there are no such elements.

The template instance serves as the document root for the selector. Only elements inside the template and its sub-templates can match parts of the selector.

Client
template.firstNode

The first top-level DOM node in this template instance.

The two nodes firstNode and lastNode indicate the extent of the rendered template in the DOM. The rendered template includes these nodes, their intervening siblings, and their descendents. These two nodes are siblings (they have the same parent), and lastNode comes after firstNode, or else they are the same node.

Client
template.lastNode

The last top-level DOM node in this template instance.

Client
template.data

The data context of this instance's latest invocation.

This property provides access to the data context at the top level of the template. It is updated each time the template is re-rendered. Access is read-only and non-reactive.

Client
template.autorun(runFunc)

A version of Tracker.autorun that is stopped when the template is destroyed.

Arguments

runFunc Function

The function to run. It receives one argument: a Tracker.Computation object.

You can use this.autorun from an onCreated or onRendered callback to reactively update the DOM or the template instance. You can use Template.currentData() inside of this callback to access reactive data context of the template instance. The Computation is automatically stopped when the template is destroyed.

Alias for template.view.autorun.

Client
template.subscribe(name, [arg1, arg2...], [options])

A version of Meteor.subscribe that is stopped when the template is destroyed.

Arguments

name String

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

購読するデータの名称。サーバ側で同じ名称が設定されたpublish()メソッドが呼び出されます。

arg1, arg2... Any

Optional arguments passed to publisher function on server.

サーバ側の配信関数へ受け渡される引数を任意で設定する。

Options

onReady Function

Passed to Meteor.subscribe.

onStop Function

Passed to Meteor.subscribe.

connection DDP Connection

The connection on which to make the subscription.

You can use this.subscribe from an onCreated callback to specify which data publications this template depends on. The subscription is automatically stopped when the template is destroyed.

There is a complementary function Template.instance().subscriptionsReady() which returns true when all of the subscriptions called with this.subscribe are ready.

Inside the template's HTML, you can use the built-in helper Template.subscriptionsReady, which is an easy pattern for showing loading indicators in your templates when they depend on data loaded from subscriptions.

Example:

Template.notifications.onCreated(function () {
  // Use this.subscribe inside onCreated callback
  this.subscribe("notifications");
});
<template name="notifications">
  {{#if Template.subscriptionsReady}}
    <!-- This is displayed when all data is ready. -->
    {{#each notifications}}
      {{> notification}}
    {{/each}}
  {{else}}
    Loading...
  {{/if}}
</template>

Another example where the subscription depends on the data context:

Template.comments.onCreated(function () {
  var self = this;

  // Use self.subscribe with the data context reactively
  self.autorun(function () {
    var dataContext = Template.currentData();
    self.subscribe("comments", dataContext.postId);
  });
});
{{#with post}}
  {{> comments postId=_id}}
{{/with}}

Another example where you want to initialize a plugin when the subscription is done:

Template.listing.onRendered(function () {
  var template = this;

  template.subscribe('listOfThings', function () {
    // Wait for the data to load using the callback
    Tracker.afterFlush(function () {
      // Use Tracker.afterFlush to wait for the UI to re-render
      // then use highlight.js to highlight a code snippet
      highlightBlock(template.find('.code'));
    });
  });
});

Client
template.view

The View object for this invocation of the template.

Client
Template.registerHelper(name, function)

Defines a helper function which can be used from all templates.

Arguments

name String

The name of the helper function you are defining.

function Function

The helper function itself.

Client
Template.instance()

The template instance corresponding to the current template helper, event handler, callback, or autorun. If there isn't one, null.

Client
Template.currentData()

  • Inside an onCreated, onRendered, or onDestroyed callback, returns the data context of the template.
  • Inside an event handler, returns the data context of the template on which this event handler was defined.
  • Inside a helper, returns the data context of the DOM node where the helper was used.

Establishes a reactive dependency on the result.

Client
Template.parentData([numLevels])

Accesses other data contexts that enclose the current data context.

Arguments

numLevels Integer

The number of levels beyond the current data context to look. Defaults to 1.

For example, Template.parentData(0) is equivalent to Template.currentData(). Template.parentData(2) is equivalent to {{../..}} in a template.

Client
Template.body

The template object representing your <body> tag.

You can define helpers and event maps on Template.body just like on any Template.myTemplate object.

Helpers on Template.body are only available in the <body> tags of your app. To register a global helper, use Template.registerHelper. Event maps on Template.body don't apply to elements added to the body via Blaze.render, jQuery, or the DOM API, or to the body element itself. To handle events on the body, window, or document, use jQuery or the DOM API.

Templates
{{> Template.dynamic template=template [data=data] }}

Choose a template to include dynamically, by name.

Arguments

template String

The name of the template to include.

data Object

Optional. The data context in which to include the template.

Template.dynamic allows you to include a template by name, where the name may be calculated by a helper and may change reactively. The data argument is optional, and if it is omitted, the current data context is used. It's also possible, to use Template.dynamic as a block helper ({{#Template.dynamic}} ... {{/Template.dynamic}})

For example, if there is a template named "foo", {{> Template.dynamic template="foo"}} is equivalent to {{> foo}} and {{#Template.dynamic template="foo"}} ... {{/Template.dynamic}} is equivalent to {{#foo}} ... {{/foo}}.

Event Maps

An event map is an object where the properties specify a set of events to handle, and the values are the handlers for those events. The property can be in one of several forms:

eventtype

Matches a particular type of event, such as 'click'.

eventtype selector

Matches a particular type of event, but only when it appears on an element that matches a certain CSS selector.

event1, event2

To handle more than one type of event with the same function, use a comma-separated list.

The handler function receives two arguments: event, an object with information about the event, and template, a template instance for the template where the handler is defined. The handler also receives some additional context data in this, depending on the context of the current element handling the event. In a template, an element's context is the data context where that element occurs, which is set by block helpers such as #with and #each.

Example:

{
  // Fires when any element is clicked
  'click': function (event) { ... },

  // Fires when any element with the 'accept' class is clicked
  'click .accept': function (event) { ... },

  // Fires when 'accept' is clicked or focused, or a key is pressed
  'click .accept, focus .accept, keypress': function (event) { ... }
}

Most events bubble up the document tree from their originating element. For example, 'click p' catches a click anywhere in a paragraph, even if the click originated on a link, span, or some other element inside the paragraph. The originating element of the event is available as the target property, while the element that matched the selector and is currently handling it is called currentTarget.

{
  'click p': function (event) {
    var paragraph = event.currentTarget; // always a P
    var clickedElement = event.target; // could be the P or a child element
  }
}

If a selector matches multiple elements that an event bubbles to, it will be called multiple times, for example in the case of 'click div' or 'click *'. If no selector is given, the handler will only be called once, on the original target element.

The following properties and methods are available on the event object passed to handlers:

type String

The event's type, such as "click", "blur" or "keypress".

target DOM Element

The element that originated the event.

currentTarget DOM Element

The element currently handling the event. This is the element that matched the selector in the event map. For events that bubble, it may be target or an ancestor of target, and its value changes as the event bubbles.

which Number

For mouse events, the number of the mouse button (1=left, 2=middle, 3=right). For key events, a character or key code.

stopPropagation()

Prevent the event from propagating (bubbling) up to other elements. Other event handlers matching the same element are still fired, in this and other event maps.

stopImmediatePropagation()

Prevent all additional event handlers from being run on this event, including other handlers in this event map, handlers reached by bubbling, and handlers in other event maps.

preventDefault()

Prevents the action the browser would normally take in response to this event, such as following a link or submitting a form. Further handlers are still called, but cannot reverse the effect.

isPropagationStopped()

Returns whether stopPropagation() has been called for this event.

isImmediatePropagationStopped()

Returns whether stopImmediatePropagation() has been called for this event.

isDefaultPrevented()

Returns whether preventDefault() has been called for this event.

Returning false from a handler is the same as calling both stopImmediatePropagation and preventDefault on the event.

Event types and their uses include:

click

Mouse click on any element, including a link, button, form control, or div. Use preventDefault() to prevent a clicked link from being followed. Some ways of activating an element from the keyboard also fire click.

dblclick

Double-click.

focus, blur

A text input field or other form control gains or loses focus. You can make any element focusable by giving it a tabindex property. Browsers differ on whether links, checkboxes, and radio buttons are natively focusable. These events do not bubble.

change

A checkbox or radio button changes state. For text fields, use blur or key events to respond to changes.

mouseenter, mouseleave

The pointer enters or leaves the bounds of an element. These events do not bubble.

mousedown, mouseup

The mouse button is newly down or up.

keydown, keypress, keyup

The user presses a keyboard key. keypress is most useful for catching typing in text fields, while keydown and keyup can be used for arrow keys or modifier keys.

Other DOM events are available as well, but for the events above, Meteor has taken some care to ensure that they work uniformly in all browsers.

Spacebars

Spacebars is the language used to write Meteor templates. It is inspired by Handlebars. It shares some of the spirit and syntax of Handlebars, but has been tailored to produce reactive Meteor templates when compiled.

For more information about Spacebars, see the Spacebars README.

Blaze

Blaze is the package that makes reactive templates possible. You can use the Blaze API directly in order to render templates programmatically and manipulate "Views," the building blocks of reactive templates. For more information, check out the Blaze project page.

Client
Blaze.render(templateOrView, parentNode, [nextNode], [parentView])

Renders a template or View to DOM nodes and inserts it into the DOM, returning a rendered View which can be passed to Blaze.remove.

Arguments

templateOrView Blaze.Template or Blaze.View

The template (e.g. Template.myTemplate) or View object to render. If a template, a View object is constructed. If a View, it must be an unrendered View, which becomes a rendered View and is returned.

parentNode DOM Node

The node that will be the parent of the rendered template. It must be an Element node.

nextNode DOM Node

Optional. If provided, must be a child of parentNode; the template will be inserted before this node. If not provided, the template will be inserted as the last child of parentNode.

parentView Blaze.View

Optional. If provided, it will be set as the rendered View's parentView.

When you render a template, the callbacks added with onCreated are invoked immediately, before evaluating the content of the template. The callbacks added with onRendered are invoked after the View is rendered and inserted into the DOM.

The rendered template will update reactively in response to data changes until the View is removed using Blaze.remove or the View's parent element is removed by Meteor or jQuery.

If the View is removed by some other mechanism besides Meteor or jQuery (which Meteor integrates with by default), the View may continue to update indefinitely. Most users will not need to manually render templates and insert them into the DOM, but if you do, be mindful to always call Blaze.remove when the View is no longer needed.

Client
Blaze.renderWithData(templateOrView, data, parentNode, [nextNode], [parentView])

Renders a template or View to DOM nodes with a data context. Otherwise identical to Blaze.render.

Arguments

templateOrView Blaze.Template or Blaze.View

The template (e.g. Template.myTemplate) or View object to render.

data Object or Function

The data context to use, or a function returning a data context. If a function is provided, it will be reactively re-run.

parentNode DOM Node

The node that will be the parent of the rendered template. It must be an Element node.

nextNode DOM Node

Optional. If provided, must be a child of parentNode; the template will be inserted before this node. If not provided, the template will be inserted as the last child of parentNode.

parentView Blaze.View

Optional. If provided, it will be set as the rendered View's parentView.

Blaze.renderWithData(Template.myTemplate, data) is essentially the same as Blaze.render(Blaze.With(data, function () { return Template.myTemplate; })).

Client
Blaze.remove(renderedView)

Removes a rendered View from the DOM, stopping all reactive updates and event listeners on it.

Arguments

renderedView Blaze.View

The return value from Blaze.render or Blaze.renderWithData.

Use Blaze.remove to remove a template or View previously inserted with Blaze.render, in such a way that any behaviors attached to the DOM by Meteor are cleaned up. The rendered template or View is now considered "destroyed", along with all nested templates and Views. In addition, any data assigned via jQuery to the DOM nodes is removed, as if the nodes were passed to jQuery's $(...).remove().

As mentioned in Blaze.render, it is important to "remove" all content rendered via Blaze.render using Blaze.remove, unless the parent node of renderedView is removed by a Meteor reactive update or with jQuery.

Blaze.remove can be used even if the DOM nodes in question have already been removed from the document, to tell Blaze to stop tracking and updating these nodes.

Client
Blaze.getData([elementOrView])

Returns the current data context, or the data context that was used when rendering a particular DOM element or View from a Meteor template.

Arguments

elementOrView DOM Element or Blaze.View

Optional. An element that was rendered by a Meteor, or a View.

Client
Blaze.toHTML(templateOrView)

Renders a template or View to a string of HTML.

Arguments

templateOrView Blaze.Template or Blaze.View

The template (e.g. Template.myTemplate) or View object from which to generate HTML.

Rendering a template to HTML loses all fine-grained reactivity. The normal way to render a template is to either include it from another template ({{> myTemplate}}) or render and insert it programmatically using Blaze.render. Only occasionally is generating HTML useful.

Because Blaze.toHTML returns a string, it is not able to update the DOM in response to reactive data changes. Instead, any reactive data changes will invalidate the current Computation if there is one (for example, an autorun that is the caller of Blaze.toHTML).

Client
Blaze.toHTMLWithData(templateOrView, data)

Renders a template or View to HTML with a data context. Otherwise identical to Blaze.toHTML.

Arguments

templateOrView Blaze.Template or Blaze.View

The template (e.g. Template.myTemplate) or View object from which to generate HTML.

data Object or Function

The data context to use, or a function returning a data context.

Client
new Blaze.View([name], renderFunction)

Constructor for a View, which represents a reactive region of DOM.

Arguments

name String

Optional. A name for this type of View. See view.name.

renderFunction Function

A function that returns renderable content. In this function, this is bound to the View.

Behind every template or part of a template — a template tag, say, like {{foo}} or {{#if}} — is a View object, which is a reactively updating region of DOM.

Most applications do not need to be aware of these Views, but they offer a way to understand and customize Meteor's rendering behavior for more advanced applications and packages.

You can obtain a View object by calling Blaze.render on a template, or by accessing template.view on a template instance.

At the heart of a View is an autorun that calls the View's renderFunction, uses the result to create DOM nodes, and replaces the contents of the View with these new DOM nodes. A View's content may consist of any number of consecutive DOM nodes (though if it is zero, a placeholder node such as a comment or an empty text node is automatically supplied). Any reactive dependency established by renderFunction causes a full recalculation of the View's contents when the dependency is invalidated. Templates, however, are compiled in such a way that they do not have top-level dependencies and so will only ever render once, while their parts may re-render many times.

When a Blaze.View is constructed by calling the constructor, no hooks are fired and no rendering is performed. In particular, the View is not yet considered to be "created." Only when the View is actually used, by a call to Blaze.render or Blaze.toHTML or by inclusion in another View, is it "created," right before it is rendered for the first time. When a View is created, its .parentView is set if appropriate, and then the onViewCreated hook is fired. The term "unrendered View" means a newly constructed View that has not been "created" or rendered.

The "current View" is kept in Blaze.currentView and is set during View rendering, callbacks, autoruns, and template event handlers. It affects calls such as Template.currentData().

The following properties and methods are available on Blaze.View:

name String

The name of this type of View. View names may be used to identify particular kinds of Views in code, but more often they simply aid in debugging and comprehensibility of the View tree. Views generated by Meteor have names like "Template.foo" and "if".

parentView View or null

The enclosing View that caused this View to be rendered, if any.

isCreated Boolean

True if this View has been called on to be rendered by Blaze.render or Blaze.toHTML or another View. Once it becomes true, never becomes false again. A "created" View's .parentView has been set to its final value. isCreated is set to true before onViewCreated hooks are called.

isRendered Boolean

True if this View has been rendered to DOM by Blaze.render or by the rendering of an enclosing View. Conversion to HTML by Blaze.toHTML doesn't count. Once true, never becomes false.

isDestroyed Boolean

True if this View has been destroyed, such as by Blaze.remove() or by a reactive update that removes it. A destroyed View's autoruns have been stopped, and its DOM nodes have generally been cleaned of all Meteor reactivity and possibly dismantled.

renderCount Integer

The number of times the View has been rendered, including the current time is the View is in the process of being rendered or re-rendered.

autorun(runFunc)

Like Tracker.autorun, except that the autorun is automatically stopped when the View is destroyed, and the current View is always set when running runFunc. There is no relationship to the View's internal autorun or render cycle. In runFunc, the View is bound to this.

onViewCreated(func)

If the View hasn't been created yet, calls func when the View is created. In func, the View is bound to this.

This hook is the basis for the created template callback.

onViewReady(func)

Calls func when the View is rendered and inserted into the DOM, after waiting for the end of flush time. Does not fire if the View is destroyed at any point before it would fire. May fire multiple times (if the View re-renders). In func, the View is bound to this.

This hook is the basis for the rendered template callback.

onViewDestroyed(func)

If the View hasn't been destroyed yet, calls func when the View is destroyed. A View may be destroyed without ever becoming "ready." In func, the View is bound to this.

This hook is the basis for the destroyed template callback.

firstNode() DOM node

The first node of the View's rendered content. Note that this may be a text node. Requires that the View be rendered. If the View rendered to zero DOM nodes, it may be a placeholder node (comment or text node). The DOM extent of a View consists of the nodes between view.firstNode() and view.lastNode(), inclusive.

lastNode() DOM node

The last node of the View's rendered content.

See firstNode().

template Template

For Views created by invoking templates, the original Template object. For example, Blaze.render(Template.foo).template === Template.foo.

templateInstance() Template instance

For Views created by invoking templates, returns the template instance object for this particular View. For example, in a created callback, this.view.templateInstance() === this.

Template instance objects have fields like data, firstNode, and lastNode which are not reactive and which are also not automatically kept up to date. Calling templateInstance() causes these fields to be updated.

Client
Blaze.currentView

The View corresponding to the current template helper, event handler, callback, or autorun. If there isn't one, null.

The "current view" is used by Template.currentData() and Template.instance() to determine the contextually relevant data context and template instance.

Client
Blaze.getView([element])

Gets either the current View, or the View enclosing the given DOM element.

Arguments

element DOM Element

Optional. If specified, the View enclosing element is returned.

If you don't specify an element, there must be a current View or an error will be thrown. This is in contrast to Blaze.currentView.

Client
Blaze.With(data, contentFunc)

Constructs a View that renders content with a data context.

Arguments

data Object or Function

An object to use as the data context, or a function returning such an object. If a function is provided, it will be reactively re-run.

contentFunc Function

A Function that returns renderable content.

Returns an unrendered View object you can pass to Blaze.render.

Unlike {{#with}} (as used in templates), Blaze.With has no "else" case, and a falsy value for the data context will not prevent the content from rendering.

Client
Blaze.If(conditionFunc, contentFunc, [elseFunc])

Constructs a View that renders content conditionally.

Arguments

conditionFunc Function

A function to reactively re-run. Whether the result is truthy or falsy determines whether contentFunc or elseFunc is shown. An empty array is considered falsy.

contentFunc Function

A Function that returns renderable content.

elseFunc Function

Optional. A Function that returns renderable content. If no elseFunc is supplied, no content is shown in the "else" case.

Returns an unrendered View object you can pass to Blaze.render.

Matches the behavior of {{#if}} in templates.

Client
Blaze.Unless(conditionFunc, contentFunc, [elseFunc])

An inverted Blaze.If.

Arguments

conditionFunc Function

A function to reactively re-run. If the result is falsy, contentFunc is shown, otherwise elseFunc is shown. An empty array is considered falsy.

contentFunc Function

A Function that returns renderable content.

elseFunc Function

Optional. A Function that returns renderable content. If no elseFunc is supplied, no content is shown in the "else" case.

Returns an unrendered View object you can pass to Blaze.render.

Matches the behavior of {{#unless}} in templates.

Client
Blaze.Each(argFunc, contentFunc, [elseFunc])

Constructs a View that renders contentFunc for each item in a sequence.

Arguments

argFunc Function

A function to reactively re-run. The function can return one of two options:

  1. An object with two fields: '_variable' and '_sequence'. Each iterates over '_sequence', it may be a Cursor, an array, null, or undefined. Inside the Each body you will be able to get the current item from the sequence using the name specified in the '_variable' field.

  2. Just a sequence (Cursor, array, null, or undefined) not wrapped into an object. Inside the Each body, the current item will be set as the data context.

contentFunc Function

A Function that returns renderable content.

elseFunc Function

A Function that returns renderable content to display in the case when there are no items in the sequence.

Returns an unrendered View object you can pass to Blaze.render.

Matches the behavior of {{#each}} in templates.

Client
new Blaze.Template([viewName], renderFunction)

Constructor for a Template, which is used to construct Views with particular name and content.

Arguments

viewName String

Optional. A name for Views constructed by this Template. See view.name.

renderFunction Function

A function that returns renderable content. This function is used as the renderFunction for Views constructed by this Template.

Templates defined by the template compiler, such as Template.myTemplate, are objects of type Blaze.Template (aliased as Template).

In addition to methods like events and helpers, documented as part of the Template API, the following fields and methods are present on template objects:

viewName String

Same as the constructor argument.

renderFunction Function

Same as the constructor argument.

constructView()

Constructs and returns an unrendered View object. This method is invoked by Meteor whenever the template is used, such as by Blaze.render or by {{> foo}} where foo resolves to a Template object.

constructView() constructs a View using viewName and renderFunction as constructor arguments, and then configures it as a template View, setting up view.template, view.templateInstance(), event maps, and so on.

Client
Blaze.isTemplate(value)

Returns true if value is a template object like Template.myTemplate.

Arguments

value Any

The value to test.

Renderable Content

A value is renderable content if it is one of the following:

  • A template object like Template.myTemplate
  • An unrendered View object, like the return value of Blaze.With
  • null or undefined

Internally, renderable content includes objects representing HTML tags as well, but these objects are not yet part of the officially-supported, public API.

Timers

Meteor uses global environment variables to keep track of things like the current request's user. To make sure these variables have the right values, you need to use Meteor.setTimeout instead of setTimeout and Meteor.setInterval instead of setInterval.

These functions work just like their native JavaScript equivalents. If you call the native function, you'll get an error stating that Meteor code must always run within a Fiber, and advising to use Meteor.bindEnvironment.

Anywhere
Meteor.setTimeout(func, delay)

Call a function in the future after waiting for a specified delay.

Arguments

func Function

The function to run

delay Number

Number of milliseconds to wait before calling function

Returns a handle that can be used by Meteor.clearTimeout.

Anywhere
Meteor.setInterval(func, delay)

Call a function repeatedly, with a time delay between calls.

Arguments

func Function

The function to run

delay Number

Number of milliseconds to wait between each function call.

Returns a handle that can be used by Meteor.clearInterval.

Anywhere
Meteor.clearTimeout(id)

Cancel a function call scheduled by Meteor.setTimeout.

Arguments

id Number

The handle returned by Meteor.setTimeout

Anywhere
Meteor.clearInterval(id)

Cancel a repeating function call scheduled by Meteor.setInterval.

Arguments

id Number

The handle returned by Meteor.setInterval

Tracker

Meteor has a simple dependency tracking system which allows it to automatically rerun templates and other computations whenever Session variables, database queries, and other data sources change.

Meteorは、Session変数、データベースクエリ、またその他のデータソースが変化した時はいつでもテンプレートとその他のコンポーネントを自動的に再実行させるための、シンプルな依存性トラッキングシステムを持っています。

Unlike most other systems, you don't have to manually declare these dependencies — it "just works". The mechanism is simple and efficient. When you call a function that supports reactive updates (such as a database query), it automatically saves the current Computation object, if any (representing, for example, the current template being rendered). Later, when the data changes, the function can "invalidate" the Computation, causing it to rerun (rerendering the template).

多くの他のシステムとは違い、これらの依存性を手動で宣言する必要はありません。 なにもしなくてもちゃんと動くのです。 メカニズムはシンプルで効果的です。 あなたがリアクティブな更新をサポートする関数(たとえばデータベースクエリなどです)を呼び出す時、 現在の演算(コンピュテーション)オブジェクト(たとえば、レンダリングされている現在のテンプレートなどを表すものです)があれば、それを自動的に保存します。 あとになってデータに変更があった時、その関数は、コンピューテーションを "インバリデート(無効化)" することができ、それはコンピューテーションを再実行させます(テンプレートのレンダリング)

Applications will find Tracker.autorun useful, while more advanced facilities such as Tracker.Dependency and onInvalidate callbacks are intended primarily for package authors implementing new reactive data sources.

アプリケーションから見ると、Tracker.autorunが有用です。 一方、より高度なTracker.DependencyonInvalidateコールバックなどの機能は、 主に新たなリアクティブ・データソースを実装するパッケージの作者達に使われることを意図しています。

Client
Tracker.autorun(runFunc, [options])

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.

実行する関数。1つの引数を取る: 演算オブジェクトを返します。

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.

オプション。runFuncでエラーが発生した時にこの関数を実行します。この関数は1つの引数を取り、発生したエラーを受け取ります。省略した場合、デフォルトではコンソールにエラーを出力します。

Tracker.autorun allows you to run a function that depends on reactive data sources, in such a way that if there are changes to the data later, the function will be rerun.

Tracker.autorunはリアクティブ・データソースに依存する関数を実行できます。 この方法をつかうと、データに後で変化があると、関数は再実行されます。

For example, you can monitor a cursor (which is a reactive data source) and aggregate it into a session variable:

例えば、カーソル(リアクティブ・データソースです)をモニターし、Session変数の中に集計結果を入れる事ができます:

Tracker.autorun(function () {
  var oldest = _.max(Monkeys.find().fetch(), function (monkey) {
    return monkey.age;
  });
  if (oldest)
    Session.set("oldest", oldest.name);
});

Or you can wait for a session variable to have a certain value, and do something the first time it does, calling stop on the computation to prevent further rerunning:

または、session変数がある値になるのを待ち、最初にその値になったとき何かをし、 演算オブジェクト(コンピューテーション)のstopを呼び、将来の再実行を防ぐことができます:

Tracker.autorun(function (c) {
  if (! Session.equals("shouldAlert", true))
    return;

  c.stop();
  alert("Oh no!");
});

The function is invoked immediately, at which point it may alert and stop right away if shouldAlert is already true. If not, the function is run again when shouldAlert becomes true.

関数はすぐに実行され、その時点で、もしshouldAlertがtrueであれば、alertとstopをその場で呼び出すかも知れません。 もしtrueでなければ、shouldAlertがtrueになった時、この関数はもう一度実行されます。

A change to a data dependency does not cause an immediate rerun, but rather "invalidates" the computation, causing it to rerun the next time a flush occurs. A flush will occur automatically as soon as the system is idle if there are invalidated computations. You can also use Tracker.flush to cause an immediate flush of all pending reruns.

データ依存性への変更は即座に再実行を引き起こしません。 そうではなく、コンピューテーション(演算)を"無効化" します。 すると、次回フラッシュが起きた時に、コンピューテーションを再実行させます。 フラッシュは、無効化されたコンピューテーションが有れば、システムがアイドル状態になるとすぐ自動的に発生します。 Tracker.flushをつかって即座にフラッシュを引き起こして、全ての未実施の再実行をフラッシュさせることもできます。

If you nest calls to Tracker.autorun, then when the outer call stops or reruns, the inner call will stop automatically. Subscriptions and observers are also automatically stopped when used as part of a computation that is rerun, allowing new ones to be established. See Meteor.subscribe for more information about subscriptions and reactivity.

もしTracker.autorunをネストして呼び出して、外側の実行が停止、または再実行する時、 内側の実行は自動的に停止します。 サブスクリプションとオブザーバーも、再実行するコンピューテーションの一部として使われた場合、新しいものを確立できるように、同様に自動的に停止します。 サブスクリプションとリアクティビティに関しての詳細は、Meteor.subscribeを御覧ください。

If the initial run of an autorun throws an exception, the computation is automatically stopped and won't be rerun.

もし、autorunの初期実行で例外が発生すると、自動的に処理は停止し、再実行されることはありません。

Client
Tracker.flush()

Process all reactive updates immediately and ensure that all invalidated computations are rerun.

全てのリアクティブな更新を即座に処理し、全ての無効化された演算(コンピューテーション)が確実に再実行されるようにする。

Normally, when you make changes (like writing to the database), their impact (like updating the DOM) is delayed until the system is idle. This keeps things predictable — you can know that the DOM won't go changing out from under your code as it runs. It's also one of the things that makes Meteor fast.

通常、あなたが変更(データベースへの書き込みなど)した場合、その影響(DOMの更新など)はシステムがアイドル状態になるまで遅延されます。 このことは、物事を予測可能に保ちます。 DOMが実行するにしたがって、あなたのコードから飛び出して変更しにいかないということを知ることができます。 これはMeteorを早くしている事の一つです。

Tracker.flush forces all of the pending reactive updates to complete. For example, if an event handler changes a Session variable that will cause part of the user interface to rerender, the handler can call flush to perform the rerender immediately and then access the resulting DOM.

Tracker.flushは、全ての未実施のリアクティブな更新を強制的に完了させます。 例えば、あるイベントハンドラが、ユーザーインターフェイスの一部の再描画を引き起こすsession変数を変更するとして、 そのハンドラは、直ちに再描画をおこない、更新後のDOMにアクセスするために、flushを呼ぶことができます。

An automatic flush occurs whenever the system is idle which performs exactly the same work as Tracker.flush. The flushing process consists of rerunning any invalidated computations. If additional invalidations happen while flushing, they are processed as part of the same flush until there is no more work to be done. Callbacks registered with Tracker.afterFlush are called after processing outstanding invalidations.

自動フラッシュは、システムがアイドル状態のときはいつでも発生し、Tracker.flushと全く同じ処理を実行します。 フラッシュのプロセスは無効化された演算(コンピューテーション)を再実行することです。 もしフラッシュしている間に追加の無効化が起こったら、同じフラッシュの一部として、これ以上の仕事がなくなるまで処理されます。 Tracker.afterFlush によって登録されたコールバックは未解決の無効な演算を処理した後に呼び出されます。

It is illegal to call flush from inside a flush or from a running computation.

flushflushの内部または実行中の演算(コンピューテーション)から呼び出すのは許されません。

The Meteor Manual describes the motivation for the flush cycle and the guarantees made by Tracker.flush and Tracker.afterFlush.

Meteor Manualには、フラッシュサイクルと Tracker.flushTracker.afterFlushによってもたらされる保証について説明があります。

Client
Tracker.nonreactive(func)

Run a function without tracking dependencies.

関数を依存性の追跡無しで実行する。

Arguments

func Function

A function to call immediately.

即座に実行される関数

Calls func with Tracker.currentComputation temporarily set to null and returns func's own return value. If func accesses reactive data sources, these data sources will never cause a rerun of the enclosing computation.

Tracker.currentComputationに一時的にnullをセットして、funcを呼び出し、func自体の戻り値を戻す。 もしfuncが、リアクティブ・データソースにアクセスしている場合、これらのデータソースは決して内部の演算(コンピューテーション)を再実行しません。

Client
Tracker.active

True if there is a current computation, meaning that dependencies on reactive data sources will be tracked and potentially cause the current computation to be rerun.

もし、現行の演算(current computation)が有ればTrue。 リアクティブ・データソースの依存性は追跡され、現行の演算(current computation)が再実行される可能性があることを意味しています。

This value is useful for data source implementations to determine whether they are being accessed reactively or not.

この値はデータソースを実装するとき、リアクティブにアクセスされているかどうかを判定するために使えます。

Client
Tracker.currentComputation

The current computation, or null if there isn't one. The current computation is the Tracker.Computation object created by the innermost active call to Tracker.autorun, and it's the computation that gains dependencies when reactive data sources are accessed.

It's very rare to need to access currentComputation directly. The current computation is used implicitly by Tracker.active (which tests whether there is one), dependency.depend() (which registers that it depends on a dependency), and Tracker.onInvalidate (which registers a callback with it).

Client
Tracker.onInvalidate(callback)

Registers a new onInvalidate callback on the current computation (which must exist), to be called immediately when the current computation is invalidated or stopped.

Arguments

callback Function

A callback function that will be invoked as func(c), where c is the computation on which the callback is registered.

See computation.onInvalidate for more details.

Client
Tracker.afterFlush(callback)

Schedules a function to be called during the next flush, or later in the current flush if one is in progress, after all invalidated computations have been rerun. The function will be run once and not on subsequent flushes unless afterFlush is called again.

Arguments

callback Function

A function to call at flush time.

Functions scheduled by multiple calls to afterFlush are guaranteed to run in the order that afterFlush was called. Functions are guaranteed to be called at a time when there are no invalidated computations that need rerunning. This means that if an afterFlush function invalidates a computation, that computation will be rerun before any other afterFlush functions are called.

Tracker.Computation

A Computation object represents code that is repeatedly rerun in response to reactive data changes. Computations don't have return values; they just perform actions, such as rerendering a template on the screen. Computations are created using Tracker.autorun. Use stop to prevent further rerunning of a computation.

Each time a computation runs, it may access various reactive data sources that serve as inputs to the computation, which are called its dependencies. At some future time, one of these dependencies may trigger the computation to be rerun by invalidating it. When this happens, the dependencies are cleared, and the computation is scheduled to be rerun at flush time.

The current computation (Tracker.currentComputation) is the computation that is currently being run or rerun (computed), and the one that gains a dependency when a reactive data source is accessed. Data sources are responsible for tracking these dependencies using Tracker.Dependency objects.

Invalidating a computation sets its invalidated property to true and immediately calls all of the computation's onInvalidate callbacks. When a flush occurs, if the computation has been invalidated and not stopped, then the computation is rerun by setting the invalidated property to false and calling the original function that was passed to Tracker.autorun. A flush will occur when the current code finishes running, or sooner if Tracker.flush is called.

Stopping a computation invalidates it (if it is valid) for the purpose of calling callbacks, but ensures that it will never be rerun.

Example:

// if we're in a computation, then perform some clean-up
// when the current computation is invalidated (rerun or
// stopped)
if (Tracker.active) {
  Tracker.onInvalidate(function () {
    x.destroy();
    y.finalize();
  });
}

Client
computation.stop()

Prevents this computation from rerunning.

Stopping a computation is irreversible and guarantees that it will never be rerun. You can stop a computation at any time, including from the computation's own run function. Stopping a computation that is already stopped has no effect.

Stopping a computation causes its onInvalidate callbacks to run immediately if it is not currently invalidated, as well as its stop callbacks.

Nested computations are stopped automatically when their enclosing computation is rerun.

Client
computation.invalidate()

Invalidates this computation so that it will be rerun.

Invalidating a computation marks it to be rerun at flush time, at which point the computation becomes valid again. It is rare to invalidate a computation manually, because reactive data sources invalidate their calling computations when they change. Reactive data sources in turn perform this invalidation using one or more Tracker.Dependency objects.

Invalidating a computation immediately calls all onInvalidate callbacks registered on it. Invalidating a computation that is currently invalidated or is stopped has no effect. A computation can invalidate itself, but if it continues to do so indefinitely, the result will be an infinite loop.

Client
computation.onInvalidate(callback)

Registers callback to run when this computation is next invalidated, or runs it immediately if the computation is already invalidated. The callback is run exactly once and not upon future invalidations unless onInvalidate is called again after the computation becomes valid again.

Arguments

callback Function

Function to be called on invalidation. Receives one argument, the computation that was invalidated.

onInvalidate registers a one-time callback that either fires immediately or as soon as the computation is next invalidated or stopped. It is used by reactive data sources to clean up resources or break dependencies when a computation is rerun or stopped.

To get a callback after a computation has been recomputed, you can call Tracker.afterFlush from onInvalidate.

Client
computation.onStop(callback)

Registers callback to run when this computation is stopped, or runs it immediately if the computation is already stopped. The callback is run after any onInvalidate callbacks.

Arguments

callback Function

Function to be called on stop. Receives one argument, the computation that was stopped.

Client
computation.stopped

True if this computation has been stopped.

Client
computation.invalidated

True if this computation has been invalidated (and not yet rerun), or if it has been stopped.

This property is initially false. It is set to true by stop() and invalidate(). It is reset to false when the computation is recomputed at flush time.

Client
computation.firstRun

True during the initial run of the computation at the time Tracker.autorun is called, and false on subsequent reruns and at other times.

This property is a convenience to support the common pattern where a computation has logic specific to the first run.

Tracker.Dependency

A Dependency represents an atomic unit of reactive data that a computation might depend on. Reactive data sources such as Session or Minimongo internally create different Dependency objects for different pieces of data, each of which may be depended on by multiple computations. When the data changes, the computations are invalidated.

Dependencies don't store data, they just track the set of computations to invalidate if something changes. Typically, a data value will be accompanied by a Dependency object that tracks the computations that depend on it, as in this example:

var weather = "sunny";
var weatherDep = new Tracker.Dependency;

var getWeather = function () {
  weatherDep.depend()
  return weather;
};

var setWeather = function (w) {
  weather = w;
  // (could add logic here to only call changed()
  // if the new value is different from the old)
  weatherDep.changed();
};

This example implements a weather data source with a simple getter and setter. The getter records that the current computation depends on the weatherDep dependency using depend(), while the setter signals the dependency to invalidate all dependent computations by calling changed().

The reason Dependencies do not store data themselves is that it can be useful to associate multiple Dependencies with the same piece of data. For example, one Dependency might represent the result of a database query, while another might represent just the number of documents in the result. A Dependency could represent whether the weather is sunny or not, or whether the temperature is above freezing. Session.equals is implemented this way for efficiency. When you call Session.equals("weather", "sunny"), the current computation is made to depend on an internal Dependency that does not change if the weather goes from, say, "rainy" to "cloudy".

Conceptually, the only two things a Dependency can do are gain a dependent and change.

A Dependency's dependent computations are always valid (they have invalidated === false). If a dependent is invalidated at any time, either by the Dependency itself or some other way, it is immediately removed.

See the Meteor Manual to learn how to create a reactive data source using Tracker.Dependency.

Client
dependency.changed()

Invalidate all dependent computations immediately and remove them as dependents.

Client
dependency.depend([fromComputation])

Declares that the current computation (or fromComputation if given) depends on dependency. The computation will be invalidated the next time dependency changes.

If there is no current computation and depend() is called with no arguments, it does nothing and returns false.

Returns true if the computation is a new dependent of dependency rather than an existing one.

Arguments

fromComputation Tracker.Computation

An optional computation declared to depend on dependency instead of the current computation.

dep.depend() is used in reactive data source implementations to record the fact that dep is being accessed from the current computation.

Client
dependency.hasDependents()

True if this Dependency has one or more dependent Computations, which would be invalidated if this Dependency were to change.

For reactive data sources that create many internal Dependencies, this function is useful to determine whether a particular Dependency is still tracking any dependency relationships or if it can be cleaned up to save memory.

ReactiveVar

To use ReactiveVar, add the reactive-var package to your project by running in your terminal:

meteor add reactive-var

Client
new ReactiveVar(initialValue, [equalsFunc])

Constructor for a ReactiveVar, which represents a single reactive variable.

Arguments

initialValue Any

The initial value to set. equalsFunc is ignored when setting the initial value.

equalsFunc Function

Optional. A function of two arguments, called on the old value and the new value whenever the ReactiveVar is set. If it returns true, no set is performed. If omitted, the default equalsFunc returns true if its arguments are === and are of type number, boolean, string, undefined, or null.

A ReactiveVar holds a single value that can be get and set, such that calling set will invalidate any Computations that called get, according to the usual contract for reactive data sources.

A ReactiveVar is similar to a Session variable, with a few differences:

  • ReactiveVars don't have global names, like the "foo" in Session.get("foo"). Instead, they may be created and used locally, for example attached to a template instance, as in: this.foo.get().

  • ReactiveVars are not automatically migrated across hot code pushes, whereas Session state is.

  • ReactiveVars can hold any value, while Session variables are limited to JSON or EJSON.

An important property of ReactiveVars — which is sometimes a reason for using one — is that setting the value to the same value as before has no effect; it does not trigger any invalidations. So if one autorun sets a ReactiveVar, and another autorun gets the ReactiveVar, a re-run of the first autorun won't necessarily trigger the second. By default, only primitive values are compared this way, while calling set on an argument that is an object (not a primitive) always counts as a change. You can configure this behavior using the equalsFunc argument.

Client
reactiveVar.get()

Returns the current value of the ReactiveVar, establishing a reactive dependency.

Client
reactiveVar.set(newValue)

Sets the current value of the ReactiveVar, invalidating the Computations that called get if newValue is different from the old value.

Arguments

newValue Any

EJSON

EJSON is an extension of JSON to support more types. It supports all JSON-safe types, as well as:

All EJSON serializations are also valid JSON. For example an object with a date and a binary buffer would be serialized in EJSON as:

{
  "d": {"$date": 1358205756553},
  "b": {"$binary": "c3VyZS4="}
}

Meteor supports all built-in EJSON data types in publishers, method arguments and results, Mongo databases, and Session variables.

Anywhere
EJSON.parse(str)

Parse a string into an EJSON value. Throws an error if the string is not valid EJSON.

Arguments

str String

A string to parse into an EJSON value.

Anywhere
EJSON.stringify(val, [options])

Serialize a value to a string.

For EJSON values, the serialization fully represents the value. For non-EJSON values, serializes the same way as JSON.stringify.

Arguments

val EJSON-able Object

A value to stringify.

Options

indent Boolean, Integer, or String

Indents objects and arrays for easy readability. When true, indents by 2 spaces; when an integer, indents by that number of spaces; and when a string, uses the string as the indentation pattern.

canonical Boolean

When true, stringifies keys in an object in sorted order.

Anywhere
EJSON.fromJSONValue(val)

Deserialize an EJSON value from its plain JSON representation.

Arguments

val JSON-compatible Object

A value to deserialize into EJSON.

Anywhere
EJSON.toJSONValue(val)

Serialize an EJSON-compatible value into its plain JSON representation.

Arguments

val EJSON-able Object

A value to serialize to plain JSON.

Anywhere
EJSON.equals(a, b, [options])

Return true if a and b are equal to each other. Return false otherwise. Uses the equals method on a if present, otherwise performs a deep comparison.

Arguments

a EJSON-able Object
b EJSON-able Object

Options

keyOrderSensitive Boolean

Compare in key sensitive order, if supported by the JavaScript implementation. For example, {a: 1, b: 2} is equal to {b: 2, a: 1} only when keyOrderSensitive is false. The default is false.

Anywhere
EJSON.clone(val)

Return a deep copy of val.

Arguments

val EJSON-able Object

A value to copy.

Anywhere
EJSON.newBinary

Allocate a new buffer of binary data that EJSON can serialize.

Arguments

size Number

The number of bytes of binary data to allocate.

Buffers of binary data are represented by Uint8Array instances on JavaScript platforms that support them. On implementations of JavaScript that do not support Uint8Array, binary data buffers are represented by standard arrays containing numbers ranging from 0 to 255, and the $Uint8ArrayPolyfill key set to true.

Anywhere
EJSON.isBinary(x)

Returns true if x is a buffer of binary data, as returned from EJSON.newBinary.

Arguments

x Object

The variable to check.

Anywhere
EJSON.addType(name, factory)

Add a custom datatype to EJSON.

Arguments

name String

A tag for your custom type; must be unique among custom data types defined in your project, and must match the result of your type's typeName method.

factory Function

A function that deserializes a JSON-compatible value into an instance of your type. This should match the serialization performed by your type's toJSONValue method.

When you add a type to EJSON, Meteor will be able to use that type in:

  • publishing objects of your type if you pass them to publish handlers.
  • allowing your type in the return values or arguments to methods.
  • storing your type client-side in Minimongo.
  • allowing your type in Session variables.

Instances of your type must implement typeName and toJSONValue methods, and may implement clone and equals methods if the default implementations are not sufficient.

Anywhere
customType.typeName()

Return the tag used to identify this type. This must match the tag used to register this type with EJSON.addType.

Anywhere
customType.toJSONValue()

Serialize this instance into a JSON-compatible value.

For example, the toJSONValue method for Mongo.ObjectID could be:

function () {
  return this.toHexString();
};

Anywhere
customType.clone()

Return a value r such that this.equals(r) is true, and modifications to r do not affect this and vice versa.

If your type does not have a clone method, EJSON.clone will use toJSONValue and the factory instead.

Anywhere
customType.equals(other)

Return true if other has a value equal to this; false otherwise.

Arguments

other Object

Another object to compare this to.

The equals method should define an equivalence relation. It should have the following properties:

  • Reflexivity - for any instance a: a.equals(a) must be true.
  • Symmetry - for any two instances a and b: a.equals(b) if and only if b.equals(a).
  • Transitivity - for any three instances a, b, and c: a.equals(b) and b.equals(c) implies a.equals(c).

If your type does not have an equals method, EJSON.equals will compare the result of calling toJSONValue instead.

HTTP

HTTP provides an HTTP request API on the client and server. To use these functions, add the HTTP package to your project by running in your terminal:

meteor add http

Anywhere
HTTP.call(method, url, [options], [asyncCallback])

Perform an outbound HTTP request.

Arguments

method String

The HTTP method to use, such as "GET", "POST", or "HEAD".

url String

The URL to retrieve.

asyncCallback Function

Optional callback. If passed, the method runs asynchronously, instead of synchronously, and calls asyncCallback. On the client, this callback is required.

Options

content String

String to use as the HTTP request body.

data Object

JSON-able object to stringify and use as the HTTP request body. Overwrites content.

query String

Query string to go in the URL. Overwrites any query string in url.

params Object

Dictionary of request parameters to be encoded and placed in the URL (for GETs) or request body (for POSTs). If content or data is specified, params will always be placed in the URL.

auth String

HTTP basic authentication string of the form "username:password"

headers Object

Dictionary of strings, headers to add to the HTTP request.

timeout Number

Maximum time in milliseconds to wait for the request before failing. There is no timeout by default.

followRedirects Boolean

If true, transparently follow HTTP redirects. Cannot be set to false on the client. Default true.

npmRequestOptions Object

On the server, HTTP.call is implemented by using the npm request module. Any options in this object will be passed directly to the request invocation.

beforeSend Function

On the client, this will be called before the request is sent to allow for more direct manipulation of the underlying XMLHttpRequest object, which will be passed as the first argument. If the callback returns false, the request will be not be send.

This function initiates an HTTP request to a remote server.

On the server, this function can be run either synchronously or asynchronously. If the callback is omitted, it runs synchronously and the results are returned once the request completes successfully. If the request was not successful, an error is thrown. This is useful when making server-to-server HTTP API calls from within Meteor methods, as the method can succeed or fail based on the results of the synchronous HTTP call. In this case, consider using this.unblock() to allow other methods on the same connection to run in the mean time. On the client, this function must be used asynchronously by passing a callback.

Both HTTP and HTTPS protocols are supported. The url argument must be an absolute URL including protocol and host name on the server, but may be relative to the current host on the client. The query option replaces the query string of url. Parameters specified in params that are put in the URL are appended to any query string. For example, with a url of "/path?query" and params of {foo:"bar"}, the final URL will be "/path?query&foo=bar".

The params are put in the URL or the request body, depending on the type of request. In the case of request with no bodies, like GET and HEAD, the parameters will always go in the URL. For a POST or other type of request, the parameters will be encoded into the body with a standard x-www-form-urlencoded content type, unless the content or data option is used to specify a body, in which case the parameters will be appended to the URL instead.

When run in asynchronous mode, the callback receives two arguments, error and result. The error argument will contain an Error if the request fails in any way, including a network error, time-out, or an HTTP status code in the 400 or 500 range. In case of a 4xx/5xx HTTP status code, the response property on error matches the contents of the result object. When run in synchronous mode, either result is returned from the function, or error is thrown.

Contents of the result object:

statusCode Number
Numeric HTTP result status code, or null on error.
content String
The body of the HTTP response as a string.
data Object or null
If the response headers indicate JSON content, this contains the body of the document parsed as a JSON object.
headers Object
A dictionary of HTTP headers from the response.

Example server method:

Meteor.methods({checkTwitter: function (userId) {
  check(userId, String);
  this.unblock();
  try {
    var result = HTTP.call("GET", "http://api.twitter.com/xyz",
                           {params: {user: userId}});
    return true;
  } catch (e) {
    // Got a network error, time-out or HTTP error in the 400 or 500 range.
    return false;
  }
}});

Example asynchronous HTTP call:

HTTP.call("POST", "http://api.twitter.com/xyz",
          {data: {some: "json", stuff: 1}},
          function (error, result) {
            if (!error) {
              Session.set("twizzled", true);
            }
          });

Anywhere
HTTP.get(url, [callOptions], [asyncCallback])

Send an HTTP GET request. Equivalent to calling HTTP.call with "GET" as the first argument.

Arguments

url String

The URL to which the request should be sent.

callOptions Object

Options passed on to HTTP.call.

asyncCallback Function

Callback that is called when the request is completed. Required on the client.

Anywhere
HTTP.post(url, [callOptions], [asyncCallback])

Send an HTTP POST request. Equivalent to calling HTTP.call with "POST" as the first argument.

Arguments

url String

The URL to which the request should be sent.

callOptions Object

Options passed on to HTTP.call.

asyncCallback Function

Callback that is called when the request is completed. Required on the client.

Anywhere
HTTP.put(url, [callOptions], [asyncCallback])

Send an HTTP PUT request. Equivalent to calling HTTP.call with "PUT" as the first argument.

Arguments

url String

The URL to which the request should be sent.

callOptions Object

Options passed on to HTTP.call.

asyncCallback Function

Callback that is called when the request is completed. Required on the client.

Anywhere
HTTP.del(url, [callOptions], [asyncCallback])

Send an HTTP DELETE request. Equivalent to calling HTTP.call with "DELETE" as the first argument. (Named del to avoid conflic with the Javascript keyword delete)

Arguments

url String

The URL to which the request should be sent.

callOptions Object

Options passed on to HTTP.call.

asyncCallback Function

Callback that is called when the request is completed. Required on the client.

Email

The email package allows sending email from a Meteor app. To use it, add the package to your project by running in your terminal:

meteor add email

The server reads from the MAIL_URL environment variable to determine how to send mail. Currently, Meteor supports sending mail over SMTP; the MAIL_URL environment variable should be of the form smtp://USERNAME:PASSWORD@HOST:PORT/. For apps deployed with meteor deploy, MAIL_URL defaults to an account (provided by Mailgun) which allows apps to send up to 200 emails per day; you may override this default by assigning to process.env.MAIL_URL before your first call to Email.send.

If MAIL_URL is not set (eg, when running your application locally), Email.send outputs the message to standard output instead.

Server
Email.send(options)

Send an email. Throws an Error on failure to contact mail server or if mail server returns an error. All fields should match RFC5322 specification.

If the MAIL_URL environment variable is set, actually sends the email. Otherwise, prints the contents of the email to standard out.

Note that this package is based on mailcomposer version 0.1.15, so make sure to refer to the documentation for that version if using the attachments or mailComposer options. Click here to read the mailcomposer 0.1.15 docs.

Options

from String

"From:" address (required)

to, cc, bcc, replyTo String or Array of Strings

"To:", "Cc:", "Bcc:", and "Reply-To:" addresses

subject String

"Subject:" line

text, html String

Mail body (in plain text and/or HTML)

headers Object

Dictionary of custom headers

attachments Array of Objects

Array of attachment objects, as described in the mailcomposer documentation.

mailComposer MailComposer

A MailComposer object representing the message to be sent. Overrides all other options. You can access the mailcomposer npm module at EmailInternals.NpmModules.mailcomposer.module.

You must provide the from option and at least one of to, cc, and bcc; all other options are optional.

Email.send only works on the server. Here is an example of how a client could use a server method call to send an email. (In an actual application, you'd need to be careful to limit the emails that a client could send, to prevent your server from being used as a relay by spammers.)

// In your server code: define a method that the client can call
Meteor.methods({
  sendEmail: function (to, from, subject, text) {
    check([to, from, subject, text], [String]);

    // Let other method calls from the same client start running,
    // without waiting for the email sending to complete.
    this.unblock();

    Email.send({
      to: to,
      from: from,
      subject: subject,
      text: text
    });
  }
});

// In your client code: asynchronously send an email
Meteor.call('sendEmail',
            'alice@example.com',
            'bob@example.com',
            'Hello from Meteor!',
            'This is a test of Email.send.');

Assets

Assets allows server code in a Meteor application to access static server assets, which are located in the private subdirectory of an application's tree. Assets are not processed as source files and are copied directly into your application's bundle.

Server
Assets.getText(assetPath, [asyncCallback])

Retrieve the contents of the static server asset as a UTF8-encoded string.

Arguments

assetPath String

The path of the asset, relative to the application's private subdirectory.

asyncCallback Function

Optional callback, which is called asynchronously with the error or result after the function is complete. If not provided, the function runs synchronously.

Server
Assets.getBinary(assetPath, [asyncCallback])

Retrieve the contents of the static server asset as an EJSON Binary.

Arguments

assetPath String

The path of the asset, relative to the application's private subdirectory.

asyncCallback Function

Optional callback, which is called asynchronously with the error or result after the function is complete. If not provided, the function runs synchronously.

Static server assets are included by placing them in the application's private subdirectory. For example, if an application's private subdirectory includes a directory called nested with a file called data.txt inside it, then server code can read data.txt by running:

var data = Assets.getText('nested/data.txt');

Note: Packages can only access their own assets. If you need to read the assets of a different package, or of the enclosing app, you need to get a reference to that package's Assets object.

Package.js

A package is a directory containing a package.js file, which contains roughly three major sections: a basic description, a package definition, and a test definition. By default, the directory name is the name of the package.

The package.js file below is an example of how to use the packaging API. The rest of this section will explain the specific API commands in greater detail.

/* Information about this package */
Package.describe({
  // Short two-sentence summary.
  summary: "What this does",
  // Version number.
  version: "1.0.0",
  // Optional.  Default is package directory name.
  name: "username:package-name",
  // Optional github URL to your source repository.
  git: "https://github.com/something/something.git",
});

/* This defines your actual package */
Package.onUse(function (api) {
  // If no version is specified for an 'api.use' dependency, use the
  // one defined in Meteor 0.9.0.
  api.versionsFrom('0.9.0');
  // Use Underscore package, but only on the server.
  // Version not specified, so it will be as of Meteor 0.9.0.
  api.use('underscore', 'server');
  // Use iron:router package, version 1.0.0 or newer.
  api.use('iron:router@1.0.0');
  // Give users of this package access to the Templating package.
  api.imply('templating')
  // Export the object 'Email' to packages or apps that use this package.
  api.export('Email', 'server');
  // Specify the source code for the package.
  api.addFiles('email.js', 'server');
});

/* This defines the tests for the package */
Package.onTest(function (api) {
  // Sets up a dependency on this package
  api.use('username:package-name');
  // Allows you to use the 'tinytest' framework
  api.use('tinytest@1.0.0');
  // Specify the source code for the package tests
  api.addFiles('email_tests.js', 'server');
});

/* This lets you use npm packages in your package*/
Npm.depends({
  simplesmtp: "0.3.10",
  "stream-buffers": "0.2.5"});

Build plugins are created with Package.registerBuildPlugin. See the coffeescript package for an example. Build plugins are fully-fledged Meteor programs in their own right and have their own namespace, package dependencies, source files and npm requirements.

Package Description

Provide basic package information with Package.describe(options). To publish a package, you must define summary and version.

package.js
Package.describe(options)

Provide basic package information.

Options

summary String

A concise 1-2 sentence description of the package, required for publication.

version String

The (extended) semver version for your package. Additionally, Meteor allows a wrap number: a positive integer that follows the version number. If you are porting another package that uses semver versioning, you may want to use the original version, postfixed with _wrapnumber. For example, 1.2.3_1 or 2.4.5-rc1_4. Wrap numbers sort after the original numbers: 1.2.3 < 1.2.3_1 < 1.2.3_2 < 1.2.4-rc.0. If no version is specified, this field defaults to 0.0.0. If you want to publish your package to the package server, you must specify a version.

name String

Optional name override. By default, the package name comes from the name of its directory.

git String

Optional Git URL to the source repository.

documentation String

Optional Filepath to documentation. Set to 'README.md' by default. Set this to null to submit no documentation.

debugOnly Boolean

A package with this flag set to true will not be bundled into production builds. This is useful for packages meant to be used in development only.

prodOnly Boolean

A package with this flag set to true will ONLY be bundled into production builds.

Package Definition

Define dependencies and expose package methods with the Package.onUse handler. This section lets you define what packages your package depends on, what packages are implied by your package, and what object your package is exported to.

package.js
Package.onUse(func)

Define package dependencies and expose package methods.

Arguments

func Function

A function that takes in the package control api object, which keeps track of dependencies and exports.

package.js
api.versionsFrom(meteorRelease)

Use versions of core packages from a release. Unless provided, all packages will default to the versions released along with meteorRelease. This will save you from having to figure out the exact versions of the core packages you want to use. For example, if the newest release of meteor is METEOR@0.9.0 and it includes jquery@1.0.0, you can write api.versionsFrom('METEOR@0.9.0') in your package, and when you later write api.use('jquery'), it will be equivalent to api.use('jquery@1.0.0'). You may specify an array of multiple releases, in which case the default value for constraints will be the "or" of the versions from each release: api.versionsFrom(['METEOR@0.9.0', 'METEOR@0.9.5']) may cause api.use('jquery') to be interpreted as api.use('jquery@1.0.0 || 2.0.0').

Arguments

meteorRelease String or Array of Strings

Specification of a release: track@version. Just 'version' (e.g. "0.9.0") is sufficient if using the default release track METEOR. Can be an array of specifications.

package.js
api.use(packageNames, [architecture], [options])

Depend on package packagename.

Arguments

packageNames String or Array of Strings

Packages being depended on. Package names may be suffixed with an @version tag.

In general, you must specify a package's version (e.g., 'accounts@1.0.0' to use version 1.0.0 or a higher compatible version (ex: 1.0.1, 1.5.0, etc.) of the accounts package). If you are sourcing core packages from a Meteor release with versionsFrom, you may leave off version names for core packages. You may also specify constraints, such as my:forms@=1.0.0 (this package demands my:forms at 1.0.0 exactly), or my:forms@1.0.0 || =2.0.1 (my:forms at 1.x.y, or exactly 2.0.1).

architecture String or Array of Strings

If you only use the package on the server (or the client), you can pass in the second argument (e.g., 'server', 'client', 'web.browser', 'web.cordova') to specify what architecture the package is used with. You can specify multiple architectures by passing in an array, for example ['web.cordova', 'os.linux'].

Options

weak Boolean

Establish a weak dependency on a package. If package A has a weak dependency on package B, it means that including A in an app does not force B to be included too — but, if B is included or by another package, then B will load before A. You can use this to make packages that optionally integrate with or enhance other packages if those packages are present. When you weakly depend on a package you don't see its exports. You can detect if the possibly-present weakly-depended-on package is there by seeing if Package.foo exists, and get its exports from the same place.

unordered Boolean

It's okay to load this dependency after your package. (In general, dependencies specified by api.use are loaded before your package.) You can use this option to break circular dependencies.

package.js
api.imply(packageNames, [architecture])

Give users of this package access to another package (by passing in the string packagename) or a collection of packages (by passing in an array of strings [packagename1, packagename2]

Arguments

packageNames String or Array of Strings

Name of a package, or array of package names, with an optional @version component for each.

architecture String or Array of Strings

If you only use the package on the server (or the client), you can pass in the second argument (e.g., 'server', 'client', 'web.browser', 'web.cordova') to specify what architecture the package is used with. You can specify multiple architectures by passing in an array, for example ['web.cordova', 'os.linux'].

package.js
api.export(exportedObjects, [architecture], [exportOptions], exportOptions.testOnly)

Export package-level variables in your package. The specified variables (declared without var in the source code) will be available to packages that use your package. If your package sets the debugOnly or prodOnly options to true when it calls Package.describe(), then packages that use your package will need to use Package["package-name"].ExportedVariableName to access the value of an exported variable.

Arguments

exportedObjects String or Array of Strings

Name of the object to export, or an array of object names.

architecture String or Array of Strings

If you only want to export the object on the server (or the client), you can pass in the second argument (e.g., 'server', 'client', 'web.browser', 'web.cordova') to specify what architecture the export is used with. You can specify multiple architectures by passing in an array, for example ['web.cordova', 'os.linux'].

exportOptions Object
exportOptions.testOnly Boolean

If true, this symbol will only be exported when running tests for this package.

package.js
api.addFiles(filenames, [architecture], [options])

Specify source code files for your package.

Arguments

filenames String or Array of Strings

Paths to the source files.

architecture String or Array of Strings

If you only want to use the file on the server (or the client), you can pass this argument (e.g., 'server', 'client', 'web.browser', 'web.cordova') to specify what architecture the file is used with. You can specify multiple architectures by passing in an array, for example ['web.cordova', 'os.linux']. By default, the file will be loaded on both server and client.

Options

bare Boolean

If this file is JavaScript code or will be compiled into JavaScript code by a build plugin, don't wrap the resulting file in a closure. Has the same effect as putting a file into the client/compatibility directory in an app.

package.js
api.addAssets(filenames, architecture)

Specify asset files for your package. They can be accessed via the Assets API from the server, or at the URL /packages/username_package-name/file-name from the client, depending on the architecture passed.

Arguments

filenames String or Array of Strings

Paths to the asset files.

architecture String or Array of Strings

Specify where this asset should be available (e.g., 'server', 'client', 'web.browser', 'web.cordova'). You can specify multiple architectures by passing in an array, for example ['web.cordova', 'os.linux'].

Unit Tests

Set up your tests with the Package.onTest handler, which has an interface that's parallel to that of the onUse handler. The tests will need to depend on the package that you have just created. For example, if your package is the email package, you have to call api.use('email') in order to test the package.

If you used meteor create to set up your package, Meteor will create the required scaffolding in package.js, and you'll only need to add unit test code in the _test.js file that was created.

package.js
Package.onTest(func)

Define dependencies and expose package methods for unit tests.

Arguments

func Function

A function that takes in the package control 'api' object, which keeps track of dependencies and exports.

External Packages and Plugins

Meteor packages can include NPM packages and Cordova plugins by using Npm.depends and Cordova.depends in the package.js file.

package.js
Npm.depends(dependencies)

Specify which NPM packages your Meteor package depends on.

Arguments

dependencies Object

An object where the keys are package names and the values are version numbers in string form or URLs to a git commit by SHA. You can only depend on exact versions of NPM packages. Example:

Npm.depends({
  moment: "2.8.3",
  async: "https://github.com/caolan/async/archive/71fa2638973dafd8761fa5457c472a312cc820fe.tar.gz"
});

Server
Npm.require(name)

Require a package that was specified using Npm.depends().

Arguments

name String

The name of the package to require.

package.js
Cordova.depends(dependencies)

Specify which Cordova / PhoneGap plugins your Meteor package depends on.

Plugins are installed from plugins.cordova.io, so the plugins and versions specified must exist there. Alternatively, the version can be replaced with a GitHub tarball URL as described in the Cordova page of the Meteor wiki on GitHub.

Arguments

dependencies Object

An object where the keys are plugin names and the values are version numbers or GitHub tarball URLs in string form. Example:

Cordova.depends({
  "org.apache.cordova.camera": "0.3.0"
});

Alternatively, with a GitHub URL:

Cordova.depends({
  "org.apache.cordova.camera":
    "https://github.com/apache/cordova-plugin-camera/tarball/d84b875c449d68937520a1b352e09f6d39044fbf"
});

package.js
Package.registerBuildPlugin([options])

Define a build plugin. A build plugin extends the build process for apps and packages that use this package. For example, the coffeescript package uses a build plugin to compile CoffeeScript source files into JavaScript.

Options

name String

A cosmetic name, must be unique in the package.

use String or Array of Strings

Meteor packages that this plugin uses, independent of the packages specified in api.onUse.

sources Array of Strings

The source files that make up the build plugin, independent from api.addFiles.

npmDependencies Object

An object where the keys are NPM package names, and the keys are the version numbers of required NPM packages, just like in Npm.depends.

Build Plugin
Plugin.registerSourceHandler(fileExtension, handler)

Inside a build plugin source file specified in Package.registerBuildPlugin, add a handler to compile files with a certain file extension.

Arguments

fileExtension String

The file extension that this plugin should handle, without the first dot. Examples: "coffee", "coffee.md".

handler Function

A function that takes one argument, a CompileStep object.

Documentation for CompileStep is available on the GitHub Wiki.

Mobile Config File

If your Meteor application targets mobile platforms such as iOS or Android, you can configure your app's metadata and build process in a special top-level file called mobile-config.js which is not included in your application and is used only for this configuration.

The code snippet below is an example mobile-config.js file. The rest of this section will explain the specific API commands in greater detail.

// This section sets up some basic app metadata,
// the entire section is optional.
App.info({
  id: 'com.example.matt.uber',
  name: 'über',
  description: 'Get über power in one button click',
  author: 'Matt Development Group',
  email: 'contact@example.com',
  website: 'http://example.com'
});

// Set up resources such as icons and launch screens.
App.icons({
  'iphone': 'icons/icon-60.png',
  'iphone_2x': 'icons/icon-60@2x.png',
  // ... more screen sizes and platforms ...
});

App.launchScreens({
  'iphone': 'splash/Default~iphone.png',
  'iphone_2x': 'splash/Default@2x~iphone.png',
  // ... more screen sizes and platforms ...
});

// Set PhoneGap/Cordova preferences
App.setPreference('BackgroundColor', '0xff0000ff');
App.setPreference('HideKeyboardFormAccessoryBar', true);
App.setPreference('Orientation', 'default');
App.setPreference('Orientation', 'all', 'ios');

// Pass preferences for a particular PhoneGap/Cordova plugin
App.configurePlugin('com.phonegap.plugins.facebookconnect', {
  APP_ID: '1234567890',
  API_KEY: 'supersecretapikey'
});

App.info(options)

Set your mobile app's core configuration information.

Options

id, version, name, description, author, email, website String

Each of the options correspond to a key in the app's core configuration as described in the Cordova documentation.

App.setPreference(name, value, [platform])

Add a preference for your build as described in the Cordova documentation.

Arguments

name String

A preference name supported by Cordova's config.xml.

value String

The value for that preference.

platform String

Optional. A platform name (either ios or android) to add a platform-specific preference.

App.accessRule(domainRule, [options])

Set a new access rule based on origin domain for your app. By default your application has a limited list of servers it can contact. Use this method to extend this list.

Default access rules:

  • tel:*, geo:*, mailto:*, sms:*, market:* are allowed and launch externally (phone app, or an email client on Android)
  • gap:*, cdv:*, file: are allowed (protocols required to access local file-system)
  • http://meteor.local/* is allowed (a domain Meteor uses to access app's assets)
  • The domain of the server passed to the build process (or local ip address in the development mode) is used to be able to contact the Meteor app server.

Read more about domain patterns in Cordova docs.

Starting with Meteor 1.0.4 access rule for all domains and protocols (<access origin="*"/>) is no longer set by default due to certain kind of possible attacks.

Arguments

domainRule String

The pattern defining affected domains or URLs.

Options

launchExternal Boolean

Set to true if the matching URL should be handled externally (e.g. phone app or email client on Android).

App.configurePlugin(id, config)

Set the build-time configuration for a Cordova plugin.

Arguments

id String

The identifier of the plugin you want to configure.

config Object

A set of key-value pairs which will be passed at build-time to configure the specified plugin.

App.icons(icons)

Set the icons for your mobile app.

Arguments

icons Object

An Object where the keys are different devices and screen sizes, and values are image paths relative to the project root directory.

Valid key values:

  • iphone
  • iphone_2x
  • iphone_3x
  • ipad
  • ipad_2x
  • android_ldpi
  • android_mdpi
  • android_hdpi
  • android_xhdpi

App.launchScreens(launchScreens)

Set the launch screen images for your mobile app.

Arguments

launchScreens Object

A dictionary where keys are different devices, screen sizes, and orientations, and the values are image paths relative to the project root directory.

For Android, launch screen images should be special "Nine-patch" image files that specify how they should be stretched. See the Android docs.

Valid key values:

  • iphone
  • iphone_2x
  • iphone5
  • iphone6
  • iphone6p_portrait
  • iphone6p_landscape
  • ipad_portrait
  • ipad_portrait_2x
  • ipad_landscape
  • ipad_landscape_2x
  • android_ldpi_portrait
  • android_ldpi_landscape
  • android_mdpi_portrait
  • android_mdpi_landscape
  • android_hdpi_portrait
  • android_hdpi_landscape
  • android_xhdpi_portrait
  • android_xhdpi_landscape

Packages

Meteor supports a variety of add-on packages and third party libraries. While you can build great applications using only the Meteor core functionality, optional packages can make development even faster and better.

Packages can be added to a Meteor project with:

meteor add <package_name>

and removed with:

meteor remove <package_name>

Some of the packages that Meteor Development Group maintains include:

appcache

The appcache package stores the static parts of a Meteor application (the client side Javascript, HTML, CSS, and images) in the browser's application cache. To enable caching simply add the appcache package to your project.

  • Once a user has visited a Meteor application for the first time and the application has been cached, on subsequent visits the web page loads faster because the browser can load the application out of the cache without contacting the server first.

  • Hot code pushes are loaded by the browser in the background while the app continues to run. Once the new code has been fully loaded the browser is able to switch over to the new code quickly.

  • The application cache allows the application to be loaded even when the browser doesn't have an Internet connection, and so enables using the app offline.

(Note however that the appcache package by itself doesn't make data available offline: in an application loaded offline, a Meteor Collection will appear to be empty in the client until the Internet becomes available and the browser is able to establish a DDP connection).

To turn AppCache off for specific browsers use:

Meteor.AppCache.config({
  chrome: false,
  firefox: false
});

The supported browsers that can be enabled or disabled include, but are not limited to, android, chrome, chromium, chromeMobileIOS, firefox, ie, mobileSafari and safari.

Browsers limit the amount of data they will put in the application cache, which can vary due to factors such as how much disk space is free. Unfortunately if your application goes over the limit rather than disabling the application cache altogether and running the application online, the browser will instead fail that particular update of the cache, leaving your users running old code.

Thus it's best to keep the size of the cache below 5MB. The appcache package will print a warning on the Meteor server console if the total size of the resources being cached is over 5MB.

If you have files too large to fit in the cache you can disable caching by URL prefix. For example,

Meteor.AppCache.config({onlineOnly: ['/online/']});

causes files in your public/online directory to not be cached, and so they will only be available online. You can then move your large files into that directory and refer to them at the new URL:

<img src="/online/bigimage.jpg">

If you'd prefer not to move your files, you can use the file names themselves as the URL prefix:

Meteor.AppCache.config({
  onlineOnly: [
    '/bigimage.jpg',
    '/largedata.json'
  ]
});

though keep in mind that since the exclusion is by prefix (this is a limitation of the application cache manifest), excluding /largedata.json will also exclude such URLs as /largedata.json.orig and /largedata.json/file1.

For more information about how Meteor interacts with the application cache, see the AppCache page in the Meteor wiki.

accounts-ui

A turn-key user interface for Meteor Accounts.

To add Accounts and a set of login controls to an application, add the accounts-ui package and at least one login provider package: accounts-password, accounts-facebook, accounts-github, accounts-google, accounts-twitter, or accounts-weibo.

Then simply add the {{> loginButtons}} helper to an HTML file. This will place a login widget on the page. If there is only one provider configured and it is an external service, this will add a login/logout button. If you use accounts-password or use multiple external login services, this will add a "Sign in" link which opens a dropdown menu with login options. If you plan to position the login dropdown in the right edge of the screen, use {{> loginButtons align="right"}} in order to get the dropdown to lay itself out without expanding off the edge of the screen.

To configure the behavior of {{> loginButtons}}, use Accounts.ui.config.

accounts-ui also includes modal popup dialogs to handle links from sendResetPasswordEmail, sendVerificationEmail, and sendEnrollmentEmail. These do not have to be manually placed in HTML: they are automatically activated when the URLs are loaded.

audit-argument-checks

This package causes Meteor to require that all arguments passed to methods and publish functions are checked. Any method that does not pass each one of its arguments to check will throw an error, which will be logged on the server and which will appear to the client as a 500 Internal server error. This is a simple way to help ensure that your app has complete check coverage.

Methods and publish functions that do not need to validate their arguments can simply run check(arguments, [Match.Any]) to satisfy the audit-argument-checks coverage checker.

coffeescript

CoffeeScript is a little language that compiles into JavaScript. It provides a simple syntax without lots of braces and parentheses. The code compiles one-to-one into the equivalent JS, and there is no interpretation at runtime.

CoffeeScript is supported on both the client and the server. Files ending with .coffee, .litcoffee, or .coffee.md are automatically compiled to JavaScript.

Namespacing and CoffeeScript

Here's how CoffeeScript works with Meteor's namespacing.

  • Per the usual CoffeeScript convention, CoffeeScript variables are file-scoped by default (visible only in the .coffee file where they are defined.)

  • When writing a package, CoffeeScript-defined variables can be exported like any other variable (see Writing Packages). Exporting a variable pulls it up to package scope, meaning that it will be visible to all of the code in your app or package (both .js and .coffee files).

  • Package-scope variables declared in .js files are visible in any .coffee files in the same app or project.

  • There is no way to make a package-scope variable from a .coffee file other than exporting it. We couldn't figure out a way to make this fit naturally inside the CoffeeScript language. If you want to use package-scope variables with CoffeeScript, one way is to make a short .js file that declares all of your package-scope variables. They can then be used and assigned to from .coffee files.

  • If you want to share variables between .coffee files in the same package, and don't want to separately declare them in a .js file, we have an experimental feature that you may like. An object called share is visible in CoffeeScript code and is shared across all .coffee files in the same package. So, you can write share.foo for a value that is shared between all CoffeeScript code in a package, but doesn't escape that package.

Heavy CoffeeScript users, please let us know how this arrangement works for you, whether share is helpful for you, and anything else you'd like to see changed.

jquery

jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development.

The jquery package adds the jQuery library to the client JavaScript bundle. It has no effect on the server.

In addition to the jquery package, Meteor provides several jQuery plugins as separate packages. These include:

less

LESS extends CSS with dynamic behavior such as variables, mixins, operations and functions. It allows for more compact stylesheets and helps reduce code duplication in CSS files.

With the less package installed, .less files in your application are automatically compiled to CSS and the results are included in the client CSS bundle.

If you want to @import a file, give it the extension .import.less to prevent Meteor from processing it independently.

markdown

This package lets you use Markdown in your templates. It's easy: just put your markdown inside {{#markdown}} ... {{/markdown}} tags. You can still use all of the usual Meteor template features inside a Markdown block, such as {{#each}}, and you still get reactivity.

Example:

{{#markdown}}I am using __markdown__.{{/markdown}}

outputs

<p>I am using <strong>markdown</strong>.</p>

oauth-encryption

Encrypts sensitive account credential information stored in the database. See packages/oauth-encryption/README.md for details.

random

The random package provides several functions for generating random numbers. It uses a cryptographically strong pseudorandom number generator when possible, but falls back to a weaker random number generator when cryptographically strong randomness is not available (on older browsers or on servers that don't have enough entropy to seed the cryptographically strong generator).

Random.id([n])

Returns a unique identifier, such as "Jjwjg6gouWLXhMGKW", that is likely to be unique in the whole world. The optional argument n specifies the length of the identifier in characters and defaults to 17.

Random.secret([n])

Returns a random string of printable characters with 6 bits of entropy per character. The optional argument n specifies the length of the secret string and defaults to 43 characters, or 256 bits of entropy. Use Random.secret for security-critical secrets that are intended for machine, rather than human, consumption.

Random.fraction()

Returns a number between 0 and 1, like Math.random.

Random.choice(arrayOrString)

Returns a random element of the given array or string.

Random.hexString(n)

Returns a random string of n hexadecimal digits.

underscore

Underscore is a utility-belt library for JavaScript that provides support for functional programming. It is invaluable for writing clear, concise JavaScript in a functional style.

The underscore package defines the _ namespace on both the client and the server.

Currently, underscore is included in all projects, as the Meteor core depends on it. _ is available in the global namespace on both the client and the server even if you do not include this package. However if you do use underscore in your application, you should still add the package as we will remove the default underscore in the future.

We have slightly modified the way Underscore differentiates between objects and arrays in collection functions. The original Underscore logic is to treat any object with a numeric length property as an array (which helps it work properly on NodeLists). In Meteor's version of Underscore, objects with a numeric length property are treated as objects if they have no prototype (specifically, if x.constructor === Object.

webapp

The webapp package is what lets your Meteor app serve content to a web browser. It is included in the meteor-base set of packages that is automatically added when you run meteor create. You can easily build a Meteor app without it - for example if you wanted to make a command-line tool that still used the Meteor package system and DDP.

This package also allows you to add handlers for HTTP requests. This lets other services access your app's data through an HTTP API, allowing it to easily interoperate with tools and frameworks that don't yet support DDP.

webapp exposes the connect API for handling requests through WebApp.connectHandlers. Here's an example that will let you handle a specific URL:

// Listen to incoming HTTP requests, can only be used on the server
WebApp.connectHandlers.use("/hello", function(req, res, next) {
  res.writeHead(200);
  res.end("Hello world from: " + Meteor.release);
});

WebApp.connectHandlers.use([path], handler) has two arguments:

path - an optional path field. This handler will only be called on paths that match this string. The match has to border on a / or a .. For example, /hello will match /hello/world and /hello.world, but not /hello_world.

handler - this is a function that takes three arguments:

  • req - a Node.js IncomingMessage object with some extra properties. This argument can be used to get information about the incoming request.
  • res - a Node.js ServerResponse object. Use this to write data that should be sent in response to the request, and call res.end() when you are done.
  • next - a function. Calling this function will pass on the handling of this request to the next relevant handler.

Command line

The following are some of the more commonly used commands in the meteor command-line tool. This is just an overview and does not mention every command or every option to every command; for more details, use the meteor help command.

meteor help

Get help on meteor command line usage. Running meteor help by itself will list the common meteor commands. Running meteor help command will print detailed help about the command.

meteor run

Run a meteor development server in the current project. Searches upward from the current directory for the root directory of a Meteor project. Whenever you change any of the application's source files, the changes are automatically detected and applied to the running application.

You can use the application by pointing your web browser at localhost:3000. No Internet connection is required.

This is the default command. Simply running meteor is the same as meteor run.

To pass additional options to Node.js use the NODE_OPTIONS environment variable. For example: NODE_OPTIONS='--debug' or NODE_OPTIONS='--debug-brk'

Run meteor help run to see the full list of options.

meteor debug

Run the project, but suspend the server process for debugging.

The server process will be suspended just before the first statement of server code that would normally execute. In order to continue execution of server code, use either the web-based Node Inspector or the command-line debugger (further instructions will be printed in the console).

Breakpoints can be set using the debugger keyword, or through the web UI of Node Inspector ("Sources" tab).

The server process debugger will listen for incoming connections from debugging clients, such as node-inspector, on port 5858 by default. To specify a different port use the --debug-port <port> option.

The same debugging functionality can be achieved by adding the --debug-port <port> option to other meteor tool commands, such as meteor run and meteor test-packages.

meteor create name

Create a new Meteor project. By default, makes a subdirectory named name and copies in the template app. You can pass an absolute or relative path.

You can use the --package option, to create a new package. If used in an existing app, this command will create a package in the packages directory.

meteor deploy site

Deploy the project in your current directory to Meteor's servers.

You can deploy to any available name under meteor.com without any additional configuration, for example, myapp.meteor.com. If you deploy to a custom domain, such as myapp.mydomain.com, then you'll need to make sure the DNS for that domain is configured to point at origin.meteor.com.

The first time you deploy an app you'll be prompted for an email address — follow the link in your email to finish setting up your account.

Once you have your account you can log in and log out from the command line, check your username with meteor whoami, and run meteor authorized to give other Meteor developers permissions to deploy your app and access its database and logs.

You can deploy in debug mode by passing --debug. This will leave your source code readable by your favorite in-browser debugger, just like it is in local development mode.

To delete an application you've deployed, specify the --delete option along with the site.

If you use a domain name other than meteor.com you must ensure that the name resolves to origin.meteor.com. If you want a top-level domain like myapp.com, you'll need a DNS A record, matching the IP address of origin.meteor.com.

You can add information specific to a particular deployment of your application by using the --settings option. The argument to --settings is a file containing any JSON string. The object in your settings file will appear on the server side of your application in Meteor.settings.

Settings are persistent. When you redeploy your app, the old value will be preserved unless you explicitly pass new settings using the --settings option. To unset Meteor.settings, pass an empty settings file.

meteor logs site

Retrieves the server logs for the named Meteor application.

Meteor redirects the output of console.log() in your server code into a logging server. meteor logs displays those logs. In client code, the output of console.log() is available in your web browser's inspector, just like any other client-side JavaScript.

meteor update

Attempts to bring you to the latest version of Meteor, and then to upgrade your packages to their latest versions. By default, update will not break compatibility.

For example, let's say packages A and B both depend on version 1.1.0 of package X. If a new version of A depends on X@2.0.0, but there is no new version of package B, running meteor update will not update A, because doing so will break package B.

You can pass in the flag --packages-only to update only the packages, and not the release itself. Similarly, you can pass in names of packages (meteor update foo:kittens baz:cats) to only update specific packages.

Every project is pinned to a specific release of Meteor. You can temporarily try using your package with another release by passing the --release option to any command; meteor update changes the pinned release.

Sometimes, Meteor will ask you to run meteor update --patch. Patch releases are special releases that contain only very minor changes (usually crucial bug fixes) from previous releases. We highly recommend that you always run update --patch when prompted.

You may also pass the --release flag to act as an override to update to a specific release. This is an override: if it cannot find compatible versions of packages, it will log a warning, but perform the update anyway. This will only change your package versions if necessary.

meteor add package

Add packages to your Meteor project. By convention, names of community packages include the name of the maintainer. For example: meteor add iron:router. You can add multiple packages with one command.

Optionally, adds version constraints. Running meteor add package@1.1.0 will add the package at version 1.1.0 or higher (but not 2.0.0 or higher). If you want to use version 1.1.0 exactly, use meteor add package@=1.1.0. You can also 'or' constraints together: for example, meteor add 'package@=1.0.0 || =2.0.1' means either 1.0.0 (exactly) or 2.0.1 (exactly).

To remove a version constraint for a specific package, run meteor add again without specifying a version. For example above, to stop using version 1.1.0 exactly, run meteor add package.

meteor remove package

Removes a package previously added to your Meteor project. For a list of the packages that your application is currently using, run meteor list.

This removes the package entirely. To continue using the package, but remove its version constraint, use meteor add.

Meteor does not downgrade transitive dependencies unless it's necessary. This means that if running meteor add A upgrades A's parent package X to a new version, your project will continue to use X at the new version even after you run meteor remove A.

meteor list

Lists all the packages that you have added to your project. For each package, lists the version that you are using. Lets you know if a newer version of that package is available.

meteor add-platform platform

Adds platforms to your Meteor project. You can add multiple platforms with one command. Once a platform has been added, you can use 'meteor run platform' to run on the platform, and meteor build to build the Meteor project for every added platform.

meteor remove-platform platform

Removes a platform previously added to your Meteor project. For a list of the platforms that your application is currently using, see meteor list-platforms.

meteor list-platforms

Lists all of the platforms that have been explicitly added to your project.

meteor mongo

Open a MongoDB shell on your local development database, so that you can view or manipulate it directly.

For now, you must already have your application running locally with meteor run. This will be easier in the future.

meteor reset

Reset the current project to a fresh state. Removes the local mongo database.

This deletes your data! Make sure you do not have any information you care about in your local mongo database by running meteor mongo. From the mongo shell, use show collections and db.collection.find() to inspect your data.

For now, you can not run this while a development server is running. Quit all running meteor applications before running this.

meteor build

Package this project up for deployment. The output is a directory with several build artifacts:

  • a tarball that includes everything necessary to run the application server (see the README in the tarball for details)
  • an unsigned apk bundle and a project source if Android is targetted as a mobile platform
  • a directory with an Xcode project source if iOS is targetted as a mobile platform

You can use the application server bundle to host a Meteor application on your own server, instead of deploying to Meteor's servers. You will have to deal with logging, monitoring, backups, load-balancing, etc, all of which we handle for you if you use meteor deploy.

The unsigned apk bundle and the outputted Xcode project can be used to deploy your mobile apps to Android Play Store and Apple App Store.

By default, your application is bundled for your current architecture. This may cause difficulties if your app contains binary code due to, for example, npm packages. You can try to override that behavior with the --architecture flag.

meteor lint

Run through the whole build process for the app and run all linters the app uses. Outputs all build errors or linting warnings to the standard output.

meteor search

Searches for Meteor packages and releases, whose names contain the specified regular expression.

meteor show

Shows more information about a specific package or release: name, summary, the usernames of its maintainers, and, if specified, its homepage and git URL.

meteor publish

Publishes your package. To publish, you must cd into the package directory, log in with your Meteor Developer Account and run meteor publish. By convention, published package names must begin with the maintainer's Meteor Developer Account username and a colon, like so: iron:router.

To publish a package for the first time, use meteor publish --create.

Sometimes packages may contain binary code specific to an architecture (for example, they may use an npm package). In that case, running publish will only upload the build to the architecture that you were using to publish it. You can use publish-for-arch to upload a build to a different architecture from a different machine.

meteor publish-for-arch

Publishes a build of an existing package version from a different architecture.

Some packages contain code specific to an architecture. Running publish by itself, will upload the build to the architecture that you were using to publish. You need to run publish-for-arch from a different architecture to upload a different build.

For example, let's say you published name:cool-binary-blob from a Mac. If you want people to be able to use cool-binary-blob from Linux, you should log into a Linux machine and then run meteor publish-for-arch name:cool-binary-blob@version. It will notice that you are on a linux machine, and that there is no Linux-compatible build for your package and publish one.

Currently, the supported architectures for Meteor are 32-bit Linux, 64-bit Linux and Mac OS. The servers for meteor deploy run 64-bit Linux.

meteor publish-release

Publishes a release of Meteor. Takes in a JSON configuration file.

Meteor releases are divided into tracks. While only MDG members can publish to the default Meteor track, anyone can create a track of their own and publish to it. Running meteor update without specifying the --release option will not cause the user to switch tracks.

To publish to a release track for the first time, use the --create-track flag.

The JSON configuration file must contain the name of the release track (track), the release version (version), various metadata, the packages specified by the release as mapped to versions (packages), and the package & version of the Meteor command-line tool (tool). Note that this means that forks of the meteor tool can be published as packages and people can use them by switching to a corresponding release. For more information, run meteor help publish-release.

meteor test-packages

Test Meteor packages, either by name, or by directory. Not specifying an argument will run tests for all local packages. The results are displayed in an app that runs at localhost:3000 by default. If you need to, you can pass the --settings and --port arguments.

meteor admin

Catch-all for miscellaneous commands that require authorization to use.

Some example uses of meteor admin include adding and removing package maintainers and setting a homepage for a package. It also includes various helpful functions for managing a Meteor release. Run meteor help admin for more information.