Meteor is an ultra-simple environment for building modern websites. What once took weeks, even with the best tools, now takes hours with Meteor. MeteorはモダンなWebサイトを作るためのとてもシンプルな環境です。従来、優れたツールを使っても何週間もかかっていたものがMeteorでは数時間になります。

The web was originally designed to work in the same way that mainframes worked in the 70s. The application server rendered a screen and sent it over the network to a dumb terminal. Whenever the user did anything, that server rerendered a whole new screen. This model served the Web well for over a decade. It gave rise to LAMP, Rails, Django, PHP.

Webとは本来、70年代のメインフレームと同じように動くよう設計されていました。そしてアプリケーションサーバは描画した画面をネットワーク経由で端末に表示させていました。ユーザが何かを実施した場合、サーバが画面全体を再描画する。このようなモデルが10年にわたってWebに残っていました。それにより、LAMPやRailsやDjangoやPHPが成長する結果となりました。

But the best teams, with the biggest budgets and the longest schedules, now build applications in JavaScript that run on the client. These apps have stellar interfaces. They don't reload pages. They are reactive: changes from any client immediately appear on everyone's screen.

しかし、優れたチームが莫大な予算と長い開発期間をかけて、今ではクライアントで動作するJavaScriptアプリケーションを開発するようになりました。そのアプリケーションはすばらしいインタフェースを備えています。ページをリロードする必要がないのです。それらはリアクティブであり、クライアントによる変更を瞬時にすべての画面へ反映されるようになりました。

They've built them the hard way. Meteor makes it an order of magnitude simpler, and a lot more fun. You can build a complete application in a weekend, or a sufficiently caffeinated hackathon. No longer do you need to provision server resources, or deploy API endpoints in the cloud, or manage a database, or wrangle an ORM layer, or swap back and forth between JavaScript and Ruby, or broadcast data invalidations to clients.

これまで製作者はアプリケーションの作成に多くの時間と労力を費やしていました。しかしMeteorはそれを桁違いに簡単にし、そして楽しくします。完璧なアプリケーションも、たった一週間で製作可能になりました。また、ハッカソンを実施するにも充実した機能を備えています。サーバの準備もすることなく、クラウドにAPIを用意することも、データベースを管理することもなく、ORMレイヤーについて悩むこともなく、JavaScriptとRubyを行き来することもなく、無効なデータをクライアントに通知する必要もありません。

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

Principles of Meteor

Meteorの特徴

  • Data on the Wire. Meteor doesn't send HTML over the network. The server sends data and lets the client render it.

    ネットワーク上のデータ. MeteorはネットワークでHTMLを送りません。サーバがデータを送り、クライアントがそれを描画します。

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

    単一の言語. Meteorでは、アプリケーションのクライアントサイドもサーバサイドも両方JavaScriptで記述します。

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

    どこでもデータベース. クライアントサイドでもサーバサイドでもデータベースにアクセスするのに同じメソッドを使うことができます。

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

    遅延の補償. クライアントサイドにおいて、Meteorはデータを事前取得しモデル変化を追従することにより、サーバのメソッド呼び出しの応答が瞬時にあったかのように見せかけます。

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

    フルスタックリアクティビティ. Meteorではリアルタイムが標準です。データベースからテンプレートまで、すべてのレイヤーにおいて必要に応じて自動で更新されます。

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

    エコシステムの採用. Meteorはオープンソースであり、既存のオープンソースのツールやフレームワークを統合します。

  • Simplicity Equals Productivity. The best way to make something seem simple is to have it actually be simple. Meteor's main functionality has clean, classically beautiful APIs.

    シンプルが導く生産性. 物事をわかりやすくに見せるための一番の方法は「シンプル」にすることです。Meteorの中心機能はクリーンで美しいAPIです。

Learning Resources

学習リソース

Fork me on GitHub

There are many community resources for getting help with your app. If Meteor catches your interest, we hope you'll get involved with the project!

Meteorには様々なアプリケーション作成を支援するコミュニティがあります。もし少しでも興味がありましたら、ぜひプロジェクトにご参加ください!

Tutorial
チュートリアル
Get started fast with the official Meteor tutorial!
Meteor公式チュートリアル
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 forums to announce projects, get help, talk about the community, or discuss changes to core.
質問をする、プロジェクトを発表するまたは、コアへの変更を議論する際はMeteorディスカッションフォーラムへアクセスしてください。
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をお読みください。

Command Line Tool

コマンドラインツール

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 meteor <command>.

meteorコマンドラインツールのヘルプを見ます。meteor helpを実行するとよく使うコマンドのリストが表示されます。meteor help <command>を実行するとmeteor <command>の詳しい使い方が表示されます。

meteor create <name>

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

<name>という名前のディレクトリを作り、そこにMeteorアプリを新しく作ります。

meteor run

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

アプリを起動し、http://localhost:3000にローカル開発サーバを用意します。

meteor debug

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

Nodeインスペクタでアプリを起動します。これにより、サーバサイドのコードをステップ実行できます。詳しくはFull APIのドキュメントを参照してください。

meteor deploy <site>

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

アプリを<site>にデプロイします。<your app>.meteor.comにデプロイした場合、Meteorは無料のホスティングを提供します。ただし、<your app>が他の人が所有されていない場合です。

meteor update

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

インストールされたMeteorを最新のバージョンにします。さらに、コマンドがアプリのディレクトリから実行された場合には、そのアプリで使用しているパッケージのバージョンを互換性が保てる範囲でアップデートします。

meteor add

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

パッケージをMeteorアプリに追加します。使えるパッケージを検索するには、meteor searchコマンドを使用します。

meteor remove

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

以前Meteorアプリに追加されたパッケージを削除します。現在使っているパッケージの一覧を表示するには、meteor listコマンドを使います。

meteor mongo

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

データベースに格納されているコレクションを閲覧もしくは操作するためのMongoDBシェルを開きます。meteor mongoでアプリのデータベースに接続するためには、あらかじめ(別のターミナルで)アプリを起動しておく必要があります。

meteor reset

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

現在のアプリを完全に新しい状態にし、すべてのローカルデータを削除します。

If you use meteor reset often, but you have some initial data that you don't want to discard, consider using Meteor.startup to recreate that data the first time the server starts up:

meteor resetをよく使う場合で、初期データを入れたい場合は、Meteor.startupを使って次のようにサーバ起動時にデータを再生成することができます。

if (Meteor.isServer) {
  Meteor.startup(function () {
    if (Rooms.find().count() === 0) {
      Rooms.insert({name: "Initial room"});
    }
  });
}

File Structure

ファイル構造

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

Meteorはとても柔軟なファイル構造をしており、どこにファイルを置いても自動的に読み込まれます。そのため、CSSやJavaScriptを読み込むための<script><link>タグは必要ありません。

Default file loading

デフォルトのファイル読み込み

If files are outside of the special directories listed below, Meteor does the following:

もし特別なディレクトリ以外にファイルを置いた場合、Meteorは次の動きをします:

  1. HTML templates are compiled and sent to the client. See the templates section for more details.
  2. HTMLテンプレートはコンパイルされクライアントに送られます。詳細はテンプレートをご確認ください。
  3. CSS files are sent to the client. In production mode they are automatically concatenated and minified.
  4. CSSファイルはクライアントに送られます。プロダクションモードでは、それらは自動的に結合されミニファイされます。
  5. JavaScript is loaded on the client and the server. You can use Meteor.isClient and Meteor.isServer to control where certain blocks of code run.
  6. JavaScriptはクライアントとサーバーの両方で読み込まれます。Meteor.isClientMeteor.isServerを使うと、クライアントまたはサーバーでのみコードを実行できます。

If you want more control over which JavaScript code is loaded on the client and the server, you can use the special directories listed below.

クライアントやサーバー上でもっとJavaScriptコードの制御を行いたい場合は、以下の特別なディレクトリを使うこともできます。

Special directories

特別なディレクトリ

/client

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

ここに置いたファイルはクライアントにのみ提供されます。ここはHTMLやCSS、UI関連のJavaScriptコードを保管するのに良い場所です。

/server

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

このディレクトリに置いたファイルはサーバーでのみ使用され、クライアントには送られません。クライアントに見られたくない極秘のロジックやデータの入ったファイルは/serverディレクトリを使用してください。

/public

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

/publicに置いたファイルはそのままクライアントに提供されます。画像などのアセットを保管するために使用します。例えば、/public/background.pngにイメージファイルを置くと、HTMLで<img src='/background.png'/>もしくはCSSでbackground-image: url(/background.png)と記述することでそのファイルを読み込むことができます。注:/publicは画像のURLに含まれません。

/private

These files can only be accessed by server code through Assets API and are not accessible to the client.

ここに置いたファイルはサーバーからはAssets API経由でのみアクセス可能で、クライアントからはアクセスできません。

Read more about file load order and special directories in the Structuring Your App section of the full API documentation.

ファイルの読み込み順番と特別なディレクトリの詳細は、full API のStructuring Your App sectionをお読みください。

Building Mobile Apps

モバイルアプリのビルド

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

ウェブアプリをMeteorで構築すると、簡単にネイティブラッパーを作成でき、わずか数コマンドでGoogle Play StoreやiOS App Storeにそのアプリを配信できます。我々はデスクトップとモバイルで同一のパッケージとAPIが動くように、多くの努力をしており、モバイルアプリ開発に関連した多くの特殊なケースについて心配する必要はありません。

Installing mobile SDKs

モバイルSDKのインストール

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

1コマンドでAndroidまたはiOSの開発ツールをインストール:

meteor install-sdk android     # for Android
meteor install-sdk ios         # for iOS

Adding platforms

プラットフォームの追加

Add the relevant platform to your app:

あなたのアプリに関連するプラットフォームを追加:

meteor add-platform android    # for Android
meteor add-platform ios        # for iOS

Running on a simulator

シミュレータで動作確認

meteor run android             # for Android
meteor run ios                 # for iOS

Running on a device

実機で動作確認

meteor run android-device      # for Android
meteor run ios-device          # for iOS

Configuring app icons and metadata

アプリのアイコンとメタデータの設定

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

特別なファイルのmobile-config.jsでアプリのアイコン、タイトル、バージョン番号、スプラッシュスクリーン、その他のメタデータを設定することができます。

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

GitHub wiki ページでモバイルサポートについて詳しく学ぶことができます。

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と示されます。

Templates

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

Meteorではビューはtemplates内に定義されます。一つのテンプレートは動的なデータを含むことのできるHTMLのスニペットです。テンプレートにはJavaScriptコードからアクセスでき、データを挿入したりイベントを待ち受けたりできます。

Defining Templates in HTML

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

テンプレートは.htmlファイルに定義されます。ファイルは複数でもよくMeteorプロジェクトディレクトリのどこにあっても構いません。ただし、次の3つのディレクトリは除きます。serverpublicprivate

Each .html file can contain any number of the following top-level elements: <head>, <body>, or <template>. Code in the <head> and <body> tags is appended to that section of the HTML page, and code inside <template> tags can be included using {{> templateName}}, as shown in the example below. Templates can be included more than once — one of the main purposes of templates is to avoid writing the same HTML multiple times by hand.

.htmlファイルには次のトップレベル要素をいくつでも含むことができます。<head><body><template><head><body>タグのコードはすべて連結されHTMLページの所定の位置に入れられます。<template>タグのコードは{{> templateName}}を使ってインクルードすることができます。次の例を参照してください。テンプレートは複数回インクルードすることができます。テンプレートは同じHTMLを複数回記述しなくすむためのものです。

<!-- add code to the <head> of the page -->
<head>
  <title>My website!</title>
</head>

<!-- add code to the <body> of the page -->
<body>
  <h1>Hello!</h1>
  {{> welcomePage}}
</body>

<!-- define a template called welcomePage -->
<template name="welcomePage">
  <p>Welcome to my website!</p>
</template>

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

{{ ... }}という文法はMeteorがHTMLを拡張するためのSpacebarsという言語の一部です。上記の例ように、テンプレートをページの任意の位置にインクルードすることができます。Spacebarsを使うとhelpersからのデータを表示することもできます。ヘルパーはJavaScriptで記述し、単なる値もしくは関数で書きます。

Client
Template.myTemplate.helpers(helpers)

Specify template helpers available to this template.

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

Arguments

helpers Object

Dictionary of helper functions by name.

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

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

下記の例は、nametagというテンプレートにnameとうヘルパー関数を定義するものです。(JavaScriptで)

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

And here is the nametag template itself (in HTML):

そしてこちらがnametagテンプレートそのものです。(HTMLで)

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

Spacebars also has a few other handy control structures that can be used to make your views more dynamic:

Spacebarsには他にもビューを動的にする便利な制御構造が用意されています。

  • {{#each data}} ... {{/each}} - Iterate over the items in data and display the HTML inside the block for each one.
  • {{#each data}} ... {{/each}} - dataの要素について繰り返し、それぞれについてブロック内のHTMLを表示する
  • {{#if data}} ... {{else}} ... {{/if}} - If data is true, display the first block; if it is false, display the second one.
  • {{#if data}} ... {{else}} ... {{/if}} - もしdatatrueならば、ひとつ目のブロックを表示する; falseならば、ふたつ目のブロックを表示する
  • {{#with data}} ... {{/with}} - Set the data context of the HTML inside, and display it.
  • {{#with data}} ... {{/with}} - ブロック内のHTMLをデータコンテキストを設定して、表示する

Each nested #each or #with block has its own data context, which is an object whose properties can be used as helpers inside the block. For #with blocks, the data context is simply the value that appears after the #with and before the }} characters. For #each blocks, each element of the given array becomes the data context while the block is evaluated for that element.

#each#withで囲まれたブロックは独自のdata contextを持ち、そのプロパティをブロック内で使うことができます。#withブロックの場合は、#with}}の間にある値が単にデータコンテキストになります。#eachブロックの場合は、与えられた配列のそれぞれの要素が、そのブロックを評価する際のデータコンテキストになります。

For instance, if the people helper has the following value

例えば、peopleヘルパーが次のような値を持つ場合

Template.welcomePage.helpers({
  people: [{name: "Bob"}, {name: "Frank"}, {name: "Alice"}]
});

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

この場合は次のようにしてすべての人の名前を<p>タグのリストで表示することができます:

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

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

もしくは<p>タグの代わりに上記の"nametag"テンプレートを使うこともできます:

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

Remember that helpers can be functions as well as simple values. For example, to show the logged in user's username, you might define a function-valued helper called username:

ヘルパーは単純な値だけでなく関数を指定することもできます。例えば、ログインユーザのユーザ名を表示するには、usernameというヘルパーに関数を指定することができます:

// in your JS file
Template.profilePage.helpers({
  username: function () {
    return Meteor.user() && Meteor.user().username;
  }
});

Now, each time you use the username helper, the helper function above will be called to determine the user's name:

このとき、usernameヘルパーを使う度に、上記のヘルパー関数が呼び出されユーザ名を決定することになります:

<!-- in your HTML -->
<template name="profilePage">
  <p>Profile page for {{username}}</p>
</template>

Helpers can also take arguments. For example, here's a helper that pluralizes a word:

ヘルパー関数は引数をとることもできます。例えば、下記は単語を複数形にする関数です:

Template.post.helpers({
  commentCount: function (numComments) {
    if (numComments === 1) {
      return "1 comment";
    } else {
      return numComments + " comments";
    }
  }
});

Pass in arguments by putting them inside the curly braces after the name of the helper:

引数は{{}}ブロック内のヘルパー名の後に指定します:

<p>There are {{commentCount 3}}.</p>

The helpers above have all been associated with specific templates, but you can also make a helper available in all templates by using Template.registerHelper.

上記のヘルパーはすべて特定のテンプレートに関連づけられていましたが、すべてのテンプレートで使えるヘルパーを作ることもできます。これには、Template.registerHelperを使います。

You can find detailed documentation for Spacebars in the README on GitHub. Later in this documentation, the sections about Session, Tracker, Collections, and Accounts will talk more about how to add dynamic data to your templates.

Spacebarsに関する詳細ドキュメントはREADME on GitHubにあります。本ドキュメント後半では、SessionTrackerCollectionsAccountsの説明があり、テンプレートに動的にデータを渡す方法についてさらに解説します。

Client
Template.myTemplate.events(eventMap)

Specify event handlers for this template.

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

Arguments

eventMap Event Map

Event handlers to associate with this template.

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

The event map passed into Template.myTemplate.events has event descriptors as its keys and event handler functions as the values. Event handlers get two arguments: the event object and the template instance. Event handlers can also access the data context of the target element in this.

Template.myTemplate.eventsに渡されるイベントハンドラはイベントディスクリプタをキーとしイベントハンドラの関数を値にしたオブジェクトです。イベントハンドラ関数は2つの引数をとります: イベントオブジェクトとテンプレートインスタンスです。また、イベントハンドラはターゲット要素のデータコンテキストにthisでアクセスできます。

To attach event handlers to the following template

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

<template name="example">
  {{#with myHelper}}
    <button class="my-button">My button</button>
    <form>
      <input type="text" name="myInput" />
      <input type="submit" value="Submit Form" />
    </form>
  {{/with}}
</template>

you might call Template.example.events as follows:

次のようにTemplate.example.eventsを呼び出します。

Template.example.events({
  "click .my-button": function (event, template) {
    alert("My button was clicked!");
  },
  "submit form": function (event, template) {
    var inputValue = event.target.myInput.value;
    var helperValue = this;
    alert(inputValue, helperValue);
  }
});

The first part of the key (before the first space) is the name of the event being captured. Pretty much any DOM event is supported. Some common ones are: click, mousedown, mouseup, mouseenter, mouseleave, keydown, keyup, keypress, focus, blur, and change.

キーの前半(スペースの前)はイベント名です。ほとんどのDOMイベントがサポートされています。よく使うものは、click, mousedown, mouseup, mouseenter, mouseleave, keydown, keyup, keypress, focus, blur, changeです。

The second part of the key (after the first space) is a CSS selector that indicates which elements to listen to. This can be almost any selector supported by JQuery.

キーの後半(スペースの後ろ)はどの要素を対象とするかを示すCSSセレクタです。これはほとんどすべてのsupported by JQueryのセレクタが使えます。

Whenever the indicated event happens on the selected element, the corresponding event handler function will be called with the relevant DOM event object and template instance. See the [Event Maps section](#eventmaps) for details.

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.

コールバック関数

The functions added with this method are called once for every instance of Template.myTemplate when it is inserted into the page for the first time.

このメソッドにより追加された関数は、Template.myTemplateのすべてのインスタンスが初めてページに挿入されるときに、一度だけ呼び出されます。

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

これらのコールバック関数は外部ライブラリを使うことに利用できます。外部ライブラリはMeteorの自動ビューレンダリングをそのままでは使えず、HTMLがページに挿入されるたびに初期化する必要があります。初期化や終了の処理はonCreatedonDestroyedのコールバック内で行うことができます。

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

例えば、codeSampleテンプレート内のすべての<pre>要素をハイライトするためにHighlightJSライブラリを使う場合は、次の関数をTemplate.codeSample.onRenderedに渡すでしょう:

Template.codeSample.onRendered(function () {
  hljs.highlightBlock(this.findAll('pre'));
});

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

コールバック関数の中では、thistemplate instanceオブジェクトになります。このオブジェクトはこのテンプレートに固有のもので再描画されても変わりません。テンプレートHTMLのDOMにアクセスするためにthis.findthis.findAllなどのメソッドを使うことができます。

Template instances

A template instance object represents a single inclusion of a template in the document. It can be used to access the HTML elements inside the template and it can be assigned properties that persist as the template is reactively updated.

テンプレートインスタンスオブジェクトはドキュメント中の一つのテンプレートの挿入に相当します。このオブジェクトはテンプレート内のHTML要素へのアクセスやプロパティ保持に使われます。プロパティはテンプレートがリアクティブに更新されても変化しません。

Template instance objects can be found in several places:

テンプレートインスタンスオブジェクトは複数の所で使用されます:

  1. The value of this in the created, rendered, and destroyed template callbacks
  2. createdrendereddestroyedのコールバック内のthisの値
  3. The second argument to event handlers
  4. イベントハンドラの第二引数
  5. As Template.instance() inside helpers
  6. ヘルパー関数内でのTemplate.instance()

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

テンプレートには追加で開発者が任意のプロパティを設定することができます。このプロパティはテンプレートの状態を保持することに使えます。例えば、Google Maps APIを使う場合に、mapオブジェクトをテンプレートインスタンスに設定し、ヘルパー関数やイベントハンドラ関数から参照することができます。初期化や終了の処理には、onCreatedonDestroyedのコールバックを使いましょう。

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. You can also use template.$, which works exactly like the JQuery $ function but only returns elements within template.

template.findAllは、selectorにマッチするDOM要素の配列を返します。また、template.$はJQueryの$と同じように使える関数です。ただし、template内の要素しか返しません。

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セレクタ。テンプレート内に限定される。

find is just like findAll but only returns the first element found. Like findAll, find only returns elements from inside the template.

findfindAllとほぼ同じですが、最初に見つかったひとつの要素だけを返します。findAllと同じく、findはテンプレート内の要素だけを返します。

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("myKey") in a template helper or inside Tracker.autorun, the relevant part of the template will be re-rendered automatically whenever Session.set("myKey", newValue) is called.

Sessionが特別なのはリアクティブであるところです。template helperTracker.autorunの中で、Session.get("myKey")と記述しておくと、どこかでSession.set("myKey", newValue)を呼び出した時に、テンプレートの関連する部分が自動的に再描画されます。

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の新しい値

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 your template -->
<template name="main">
  <p>We've always been at war with {{theEnemy}}.</p>
</template>
// In your JavaScript
Template.main.helpers({
  theEnemy: function () {
    return Session.get("enemy");
  }
});

Session.set("enemy", "Eastasia");
// Page will say "We've always been at war with Eastasia"

Session.set("enemy", "Eurasia");
// Page will change to say "We've always been at war with Eurasia"

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

Sessionを使うと、renderファンクションを手動で呼び出すことなく、必要に応じて自動でビューを更新するリアクティビティの一端に触れることができます。次のセクションでは、Meteorでこれを可能にしている軽量ライブラリTrackerの使い方を学習します。

Tracker

Meteor has a simple dependency tracking system which allows it to automatically rerun templates and other functions 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. Once you've initialized a computation with Tracker.autorun, whenever you call a Meteor function that returns data, Tracker automatically records which data were accessed. Later, when this data changes, the computation is rerun automatically. This is how a template knows how to re-render whenever its helper functions have new data to return.

他のほとんどのシステムとは異なり、手動でこれらの依存関係を宣言する必要はありません。特に何もしなくても動きます。そのメカニズムはシンプルかつ効率的です。Tracker.autorunで処理を初期化すると、データを返すMeteor関数を呼び出した場合に、どのデータにアクセスしたかが自動で記録されます。その後、そのデータが変更されると、処理が自動的に再実行されます。このようにして、ヘルパー関数が新しいデータを返すとテンプレートは再レンダリングが必要なことを検知できます。

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. Whenever those data sources are updated with new data, the function will be rerun.

Tracker.autorunはリアクティブデータソースに依存した関数を実行できるようにします。これらのデータソースが新しいデータで更新されるたびに、その関数は再実行されます。

For example, you can monitor one Session variable and set another:

例えば、1つのSession変数を監視し、それを別のものにセットすることができます:

Tracker.autorun(function () {
  var celsius = Session.get("celsius");
  Session.set("fahrenheit", celsius * 9/5 + 32);
});

Or you can wait for a session variable to have a certain value, and do something the first time it does. If you want to prevent further rerunning of the function, you can call stop on the computation object that is passed as the first parameter to the callback function:

また、Session変数が特定の値になった時に初めて処理を実行するようにもできます。もし、これ以上関数を再実行させたくなければ、コールバック関数の第1引数に渡される演算オブジェクトのstopを呼び出すことで、再実行しないようにできます。

// Initialize a session variable called "counter" to 0
Session.set("counter", 0);

// The autorun function runs but does not alert (counter: 0)
Tracker.autorun(function (computation) {
  if (Session.get("counter") === 2) {
    computation.stop();
    alert("counter reached two");
  }
});

// The autorun function runs but does not alert (counter: 1)
Session.set("counter", Session.get("counter") + 1);

// The autorun function runs and alerts "counter reached two"
Session.set("counter", Session.get("counter") + 1);

// The autorun function no longer runs (counter: 3)
Session.set("counter", Session.get("counter") + 1);

The first time Tracker.autorun is called, the callback function is invoked immediately, at which point it alerts and stops right away if counter === 2 already. In this example, Session.get("counter") === 0 when Tracker.autorun is called, so nothing happens the first time, and the function is run again each time counter changes, until computation.stop() is called after counter reaches 2.

初めてTracker.autorunが呼ばれると、コールバック関数はすぐに実行され、もしすでに counter === 2 の場合は、アラートを表示してすぐに停止します。上の例では、Tracker.autorunが呼ばれた時は Session.get("counter") === 0 なので、初めは何も起きません。そして、counter2になりcomputation.stop()が呼ばれるまでは、counterが変更されるたびに関数が実行されます。

If the initial run of an autorun throws an exception, the computation is automatically stopped and won't be rerun.

もし、autorunの初期実行で例外が発生すると、自動的に処理は停止し、再実行されることはありません。

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

Trackerの動きについてもっと学習したり、高度な使い方を知りたい場合は、Meteor ManualTrackerチャプターにより詳細な説明があります。

Collections

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

Meteorはコレクションの中にデータを保存します。コレクションの中に保存されたJavaScriptオブジェクトはdocuments(ドキュメント)と呼ばれます。開始するには、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を指定した場合、管理されない(同期されない)ローカルコレクションを作ります。

Calling the Mongo.Collection constructor creates a collection object which acts just like a MongoDB collection. If you pass a name when you create the collection, then you are declaring a persistent collection — one that is stored on the server and can be published to clients.

Mongo.Collectionコンストラクタを呼び出すと、ちょうどMongoDBコレクションのように動作するコレクション・オブジェクトを作成します。コレクションを作成する時に名前を渡すと、永続的なコレクションの宣言になります。それはサーバーに保存され、クライアントに配信することができます。

To allow both client code and server code to access the same collection using the same API, it's usually best to declare collections as global variables in a JavaScript file that's present on both client and server.

クライアントコードとサーバーコードの両方が同じAPIを使用して同じコレクションにアクセスできるようにするには、クライアントとサーバーの両方で使用されるJavaScriptファイル内で、グローバル変数としてコレクションを宣言します。

Here's an example of declaring two named, persistent collections as global variables:

ここで、グローバル変数として永続的なコレクションを2つ宣言する例を示します:

// In a JS file that's loaded on the client and the server
Posts = new Mongo.Collection("posts");
Comments = new Mongo.Collection("comments");

If you pass null as the name, then you're creating a local collection. Local collections are not synchronized between the client and the server; they are just temporary collections of JavaScript objects that support Mongo-style find, insert, update, and remove operations.

もしnullを名前に渡すと、ローカルコレクションを作成します。ローカルコレクションはクライアントとサーバー間で同期されません。これらはMongoスタイルのfindinsertupdateremoveをサポートしたJavaScriptオブジェクトの一時的なコレクションとなります。

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

デフォルトでは、Meteorは自動的にあなたのコレクションのすべてのドキュメントを接続しているクライアントに配信します。この振る舞いを止めるには、ターミナルで以下のコマンドを実行して、autopublishパッケージを取り除く必要があります:

meteor remove autopublish

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

それから、コレクションの一部をどのクライアントに配信するかを指定するため、Meteor.publishMeteor.subscribeを使用します。

Use findOne or find to retrieve documents from a collection.

コレクションからドキュメントを取得するには、findOnefindを使用します。

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 除外するフィールド

This method lets you retrieve a specific document from your collection. The findOne method is most commonly called with a specific document _id:

このメソッドは特定のドキュメントをコレクションから取得します。findOneメソッドは特定のドキュメント_idと共に呼び出されるのが最も一般的です:

var post = Posts.findOne(postId);

However, you can also call findOne with a Mongo selector, which is an object that specifies a required set of attributes of the desired document. For example, this selector

しかしながら、ドキュメントの属性のセットを細かく指定したMongoセレクタでfindOneを呼び出すこともできます。たとえば、このセレクタは:

var post = Posts.findOne({
  createdBy: "12345",
  title: {$regex: /first/}
});

will match this document

このドキュメントにマッチします

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

You can read about MongoDB query operators such as $regex, $lt (less than), $text (text search), and more in the MongoDB documentation.

$regex (正規表現)、$lt (より小さい)、$text (テキスト検索)など多くのMongoDBクエリ操作について、詳しくはMongoDBドキュメントをご覧ください。

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

明確ではないかもしれませんが、ひとつの便利な動作として、Mongoセレクタは配列内の要素にもマッチします。たとえば、このセレクタは

Post.findOne({
  tags: "meteor"
});

will match this document

このドキュメントにマッチします

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

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

findOneメソッドはSession.getのようにリアクティブです。すなわち、テンプレートヘルパーの中やTracker.autorunのコールバックで使用すると、ドキュメントが更新された時に自動的に表示が再描画されたり、計算処理が再実行されます。

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

注:findOneはマッチするドキュメントが見つからなかった時にnullを返します。それはドキュメントがまだ読み込まれていなかったり、コレクションからドキュメントを取り除いた時に頻繁に起こります。そのためnull値の場合の処理を用意する必要があります。

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 除外するフィールド

The find method is similar to findOne, but instead of returning a single document it returns a MongoDB cursor. A cursor is a special object that represents a list of documents that might be returned from a query. You can pass a cursor into a template helper anywhere you could pass an array:

findメソッドはfindOneと似ていますが、一つのドキュメントの代わりに、MongoDBカーソルを返します。カーソルは、クエリから返される可能性があるドキュメントのリストを表す特別なオブジェクトです。テンプレートヘルパーの中で配列を渡すことができる場所ならどこでもカーソルを渡すことができます:

Template.blog.helpers({
  posts: function () {
    // this helper returns a cursor of
    // all of the posts in the collection
    return Posts.find();
  }
});
<!-- a template that renders multiple posts -->
<template name="blog">
  {{#each posts}}
    <h1>{{title}}</h1>
    <p>{{content}}</p>
  {{/each}}
</template>

When you want to retrieve the current list of documents from a cursor, call the cursor's .fetch() method:

カーソルからドキュメントのリストを取り出すには、カーソルの.fetch()メソッドを呼び出します:

// get an array of posts
var postsArray = Posts.find().fetch();

Keep in mind that while the computation in which you call fetch will rerun when the data changes, the resulting array will not be reactive if it is passed somewhere else.

注意すべきは、データが更新されたときにfetch自体の計算は再実行されますが、その結果の配列はリアクティブではないため別のところに渡した場合は更新されなくなる点です。

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

Mongo.Collectionの中に保存されたデータはinsertupdateremoveを呼ぶことで変更できます。

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引数に渡します。

Here's how you insert a document into a collection:

コレクションにドキュメントを挿入する方法は次の通りです:

Posts.insert({
  createdBy: Meteor.userId(),
  createdAt: new Date(),
  title: "My first post!",
  content: "Today was a good day."
});

Every document in every Mongo.Collection has an _id field. It must be unique, and is automatically generated if you don't provide one. The _id field can be used to retrieve a specific document using collection.findOne.

すべてのMongo.Collectionのすべてのドキュメントは、_idフィールドを持っています。それは一意であり、_idを指定しなかった時は自動的に生成されます。_idフィールドはcollection.findOneで特定のドキュメントを取得するために使用できます。

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ならマッチするドキュメントが見つからなかった場合にドキュメントを新たに挿入します。

The selector here is just like the one you would pass to find, and can match multiple documents. The modifier is an object that specifies which changes should be made to the matched documents. Watch out - unless you use an operator like $set, update will simply replace the entire matched document with the modifier.

selectorはfindメソッドに渡すのと同じようなもので、複数のドキュメントにマッチします。modifierはマッチしたドキュメントをどのように修正するかを記述したオブジェクトです。注:modifierで$setオペレーターを指定しない場合、updateはマッチしたドキュメントをmodifierとまるごと交換します。

Here's an example of setting the content field on all posts whose titles contain the word "first":

ここで、タイトルに"first"を含むすべてのpostsに、contentフィールドをセットする例を示します:

Posts.update({
  title: {$regex: /first/}
}, {
  $set: {content: "Tomorrow will be a great day."}
});

You can read about all of the different operators that are supported in the MongoDB documentation.

updateの各オペレーターについてはMongoDB documentationで知ることができます。

There's one catch: when you call update on the client, you can only find documents by their _id field. To use all of the possible selectors, you must call update in server code or from a method.

注:クライアント上でupdateを呼び出した場合、_idフィールドでのみドキュメントを見つけることができます。セレクタに他のものを使用する場合は、サーバーコードかmethod経由でupdateを呼び出す必要があります。

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.

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

This method uses the same selectors as find and update, and removes any documents that match the selector from the database. Use remove carefully — there's no way to get that data back.

このメソッドはfindupdateと同じセレクタが使用でき、セレクタにマッチしたドキュメントをデータベースから取り除きます。removeを使用するときは気をつけて下さい — 削除されたデータを再び取得する方法はありません。

As with update, client code can only remove documents by _id, whereas server code and methods can remove documents using any selector.

updateと同様に、クライアントコードでは_idでのみドキュメントを削除できます。一方で、サーバーコードやmethodsであれば他のセレクタを使用してドキュメントを削除することができます。

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を返す関数です。

In newly created apps, Meteor allows almost any calls to insert, update, and remove from any client or server code. This is because apps started with meteor create include the insecure package by default to simplify development. Obviously, if any user could change the database whenever they wanted it would be bad for security, so it is important to remove the insecure package and specify some permissions rules, in your terminal:

新しく作成されたアプリでは、Meteorはクライアントまたはサーバーコードからのほとんどのinsertupdateremoveの呼び出しを許可します。これはmeteor createで始めたアプリには、デフォルトでシンプルに開発を行うためのinsecureパッケージが含まれているためです。当然ながら、誰もがどんな時にもデータベースを変更できるというのはセキュリティ的に良くありません。そこで、insecureパッケージを取り除き、いくつかのアクセス許可ルールを指定することが重要です。ターミナルで:

meteor remove insecure

Once you have removed the insecure package, use the allow and deny methods to control who can perform which operations on the database. By default, all operations on the client are denied, so we need to add some allow rules. Keep in mind that server code and code inside methods are not affected by allow and deny — these rules only apply when insert, update, and remove are called from untrusted client code.

一度insecureを取り除いたら、データベース操作を行えるユーザーをコントロールするためにallowdenyメソッドを使用します。デフォルトでは、クライアント上でのすべての操作は拒否されるため、いくつかの許可ルールの追加が必要です。注意すべきは、サーバーコードとmethodsのコード内では、allowdenyは影響を与えない点です — これらのルールは、信頼されないクライアントコードからのinsertupdateremoveにのみ適用されます。

For example, we might say that users can only create new posts if the createdBy field matches the ID of the current user, so that users can't impersonate each other.

たとえば、現在のユーザーのIDとcreatedByフィールドがマッチする場合のみ新しい記事を作成できるようにすると、他のユーザーがなりすましできなくなるでしょう。

// In a file loaded on the server (ignored on the client)
Posts.allow({
  insert: function (userId, post) {
    // can only create posts where you are the author
    return post.createdBy === userId;
  },
  remove: function (userId, post) {
    // can only delete your own posts
    return post.createdBy === userId;
  }
  // since there is no update field, all updates
  // are automatically denied
});

The allow method accepts three possible callbacks: insert, remove, and update. The first argument to all three callbacks is the _id of the logged in user, and the remaining arguments are as follows:

allowメソッドは次の3つのコールバックを受け付けます: insertremoveupdate。すべてのコールバックの第1引数には現在ログインしているユーザの_idが渡されます。残りの引数は次の通りです:

  1. insert(userId, document)

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

    documentはデータベースに挿入されようとしているドキュメントです。もし挿入を許可すべきならtrueを返し、そうでなければfalseを返します。

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

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

    documentは変更されようとしているドキュメントです。fieldNamesはこの変更によって影響を受ける最上位フィールドの配列です。modifiercollection.updateの第2引数に渡されたMongo Modifierです。このコールバックを使用して正しい検証を行うのは難しいため、その場合はmethodsを代わりに使用することをおすすめします。更新を許可すべきならtrueを返し、そうでなければfalseを返します。

  3. remove(userId, document)

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

    documentはデータベースから削除されようとしているドキュメントです。削除を許可すべきならtrueを返し、そうでなければfalseを返します。

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ルールで上書きされます

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

denyメソッドを使用して、allowルールを選択的に上書きできます。allowコールバックのいずれかがtrueを返し、全てのdenyコールバックがfalseを返すことでデータベースの変更が許可されます。

For example, if we wanted to override part of our allow rule above to exclude certain post titles:

たとえば、前にでてきたallowルールを上書きして、特定のタイトルの記事を除外したい場合は、以下のように記述します:

// In a file loaded on the server (ignored on the client)
Posts.deny({
  insert: function (userId, post) {
    // Don't allow posts with a certain title
    return post.title === "First!";
  }
});

Accounts

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

アカウント機能を使うには、下記のパッケージをひとつ以上追加する必要があります。meteor addコマンドを使います:

  • accounts-ui: This package allows you to use {{> loginButtons}} in your templates to add an automatically generated UI that will let users log into your app. There are several community alternatives to this package that change the appearance, or you can not use it and use the advanced Accounts methods instead.
  • accounts-ui: このパッケージはテンプレートで{{> loginButtons}}を使えるようにするもので、アプリのログイン機能のUIが自動で生成されまます。これ以外にも複数のコミュニティパッケージがあり、表示スタイルを変更することができます。また、これらを使わなくてもadvanced Accounts methodsのAPIを直接使うこともできます。
  • accounts-password: This package will allow users to log in with passwords. When you add it the loginButtons dropdown will automatically gain email and password fields.
  • accounts-password: このパッケージはユーザがパスワードでログインできるようにするものです。このパッケージを追加すると、loginButtonsのドロップダウンに自動でemailとパスワードのフィールドが追加されます。
  • accounts-facebook, accounts-google, accounts-github, accounts-twitter, and community packages for other services will allow your users to log in with their accounts from other websites. These will automatically add buttons to the loginButtons dropdown.
  • accounts-facebookaccounts-googleaccounts-githubaccounts-twitterや、その他サービス向けのコミュニティパッケージは、ユーザが他のサイトのアカウントでログインできるようにするものです。自動でloginButtonsのドロップダウンにログイン用のボタンが追加されます。

{{> loginButtons}} Client

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

loginButtonsのテンプレートをHTMLのどこかに設置すると、MeteorのデフォルトのログインUIが使えます。これを使うには、次のようにaccounts-uiパッケージを追加する必要があります:

meteor add accounts-ui

Anywhere but publish functions
Meteor.user()

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

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

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

Meteor.usersコレクションからログインユーザのデータを取得します。Meteor.users.findOne(Meteor.userId())と同等です。

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 (by default) the user can create and update with any data.
  • profile: (デフォルトでは)ユーザが任意のデータを作成したり更新したりできるオブジェクト。
  • 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; }});

{{ currentUser }}

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

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

Methods

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

Methods(メソッド)はクライアントから呼ばれるサーバー関数です. これらは、insertupdateremoveよりもっと複雑に何かをしたい状況や、allowdenyだけでは難しいデータバリデーションが必要な状況で便利なものです。

Methods can return values and throw errors.

Methods(メソッド)は戻り値とエラーを返します。

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.

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

Calling Meteor.methods on the server defines functions that can be called remotely by clients. Here's an example of a method that checks its arguments and throws an error:

サーバー上でのMeteor.methodsの呼び出しは、クライアント側からリモートで呼び出すことのできる関数を定義します。ここでは、引数のチェックとエラーを返すメソッドの一例を示しています。

// On the server
Meteor.methods({
  commentOnPost: function (comment, postId) {
    // Check argument types
    check(comment, String);
    check(postId, String);

    if (! this.userId) {
      throw new Meteor.Error("not-logged-in",
        "Must be logged in to post a comment.");
    }

    // ... do stuff ...

    return "something";
  },

  otherMethod: function () {
    // ... do other stuff ...
  }
});

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

ここでのcheck関数は、期待されるメソッド引数のtypesとstructureを強制実行するための一つの便利な方法です。

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

メソッド定義上で、thisはメソッド呼び出しにバインドされたオブジェクトです。thisはいくつかの便利なプロパティを持ち、その内のthis.userIdは現状ログインしているユーザーを確認します。

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呼び出しにメソッド定義全てを置く必要はありません。ユニークな名前を各メソッドが持つ限り、あなたはこれを複数回呼び出すでしょう。

Latency Compensation

Calling a method on the server requires a round-trip over the network. It would be really frustrating if users had to wait a whole second to see their comment show up due to this delay. That's why Meteor has a feature called method stubs. If you define a method on the client with the same name as a server method, Meteor will run it to attempt to predict the outcome of the server method. When the code on the server actually finishes, the prediction generated on the client will be replaced with the actual outcome of the server method.

サーバー上でのメソッド呼び出しは、ネットワーク越しに往復が必要になります。例えば、このネットワークの往復によるディレイによって、ユーザーがコメントを表示させるのに数秒間待たなくてはならないのは非常にストレスになります。なぜならMeteorはmethod stubsという特徴を持っているからです。もし、あなたがクライアント上で一つのメソッドを一つのサーバーメソッドとして同じ名前で定義した場合、Meteorはサーバーメソッドからの結果を予測して試みる為に実行します。実際にサーバー上でコードが終了すると、クライアント上で生成されたその予測はサーバーメソッドの実際の結果に置き換えられます。

The client versions of insert, update, and remove, which are implemented as methods, use this feature to make client-side interactions with the database appear instant.

メソッドとして実装されたクライアント版のinsertupdateremoveは、クライアント側のインタラクションとデータベースに即時反映させるためにこの特徴を使います。

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 you call a method.

以下は、メソッドの呼び出し方です。

On the client

Methods called on the client run asynchronously, so you need to pass a callback in order to observe the result of the call. The callback will be called with two arguments, error and result. The error argument will be null unless an exception was thrown. When an exception is thrown, the error argument is a Meteor.Error instance and the result argument is undefined.

メソッドはクライアント上で非同期的に実行されるので、呼び出し結果を監視するためにコールバックを渡す必要があります。そのコールバックはerrorresultの2つを引数として持ち、呼びだされます。error引数は、例外が投げられない限りnullを返します。例外が投げられた場合、error引数はMeteor.Errorインスタンスとなり、resultはundefinedとなります。

Here's an example of calling the commentOnPost method with arguments comment and postId:

ここでの例では、commentOnPostメソッドをcommentpostIdの引数と共に呼び出しています。

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

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

Meteorはメソッド呼び出しの一部として機能したデータベースアップデートを追跡し、クライアントサイドのコールバックを呼び出すためにクライアントへそれら全てのアップデートが送られるまで待ちます。

On the server

On the server, you don't have to pass a callback — the method call will simply block until the method is complete, returning a result or throwing an exception, just as if you called the function directly:

サーバー上では、コールバックを渡す必要はありません(ただ単に直接的に関数を呼び出すと、メソッドが結果や例外を返し完了するまでメソッド呼び出しは単純にブロックします)

// Synchronous call on the server with no callback
var result = Meteor.call('commentOnPost', comment, postId);

Anywhere
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 will be sent to the client. If a method function throws a different exception, the client gets Meteor.Error(500, 'Internal server error').

もし、メソッドから何かエラーを返してほしいならば、例外を投げてください。メソッドはいくつかの例外の種類を投げることができますが、Meteor.Errorは唯一のクライアントへ送信されるエラーの種類です。もし何かのメソッド関数が異なる例外を投げる場合、クライアントはMeteor.Error(500, 'Internal server error')を受け取ります。

Publish and subscribe

Meteor servers can publish sets of documents with Meteor.publish, and clients can subscribe to those publications with Meteor.subscribe. Any documents the client subscribes to will be available through the find method of client collections.

Meteorのサーバは、Meteor.publishメソッドによりドキュメントのセットを配信し、クライアントではMeteor.subscribeメソッドで配信されたドキュメントを購読することができます。購読されたドキュメントは、クライアント側のfindメソッドにより利用できるようになります。

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

デフォルトでは、新規作成されたMeteorアプリケーションにはautopublishパッケージが予め同梱されており、全ての利用可能なドキュメントは、全てのクライアントに自動で配信されます。クライアントそれぞれに配信するドキュメントをより細やかに制御したい場合、まずターミナル上で以下のコマンドを入力し、autopublishパッケージを削除しましょう。

meteor remove autopublish

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

これで、Meteor.publishMeteor.subscribeを使って、どのドキュメントをサーバからクライアントへ流すかを制御できるようになります。

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 data to clients, call Meteor.publish on the server with two arguments: the name of the record set, and a publish function that will be called each time a client subscribes to this record set.

クライアントにデータを配信するには、サーバ側で以下の2つの引数をセットしてMeteor.publishメソッドを実行します。1つは配信データの名称。もう1つは、クライアント側で配信データへの購読要求が行われるたびに呼び出される配信関数です。

Publish functions typically return the result of calling collection.find(query) on some collection with a query that narrows down the set of documents to publish from that collection:

配信関数では一般的に、配信するドキュメントのセットをcollection.find(query)によって絞りこんで取得し返却します。

// Publish the logged in user's posts
Meteor.publish("posts", function () {
  return Posts.find({ createdBy: this.userId });
});

You can publish documents from multiple collections by returning an array of collection.find results:

collection.findの結果を配列として返すことで、複数のコレクションから取得したドキュメントを配信することも可能です。

// Publish a single post and its comments
Meteor.publish("postAndComments", function (postId) {
  // Check argument
  check(postId, String);

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

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

配信関数の処理内では、this.userIdは現在ログインしているユーザの_idを指し示しており、これは、特定のドキュメントを特定のユーザにのみ表示するよう制限をかけるのに役立ちます。 もし、クライアントのログインユーザが変わると、配信関数は自動的に新しいユーザのuserIdを元に再実行されるため、新しいユーザは以前のユーザに対してのみ提供されていたドキュメントにはアクセスできなくなります。

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メソッドのコールバック関数として解釈されます。

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

クライアント側でMeteor.subscribeメソッドを呼び出すことで、サーバから配信されたドキュメントのコレクションに対する関係性を明示します。クライアント側でcollection.find(query)を使うと、ドキュメントのコレクションを更に絞り込んで取得することもできます。サーバ側で配信関数が手に入れたデータに変更があった場合、配信関数は自動的に再実行され、更新されたドキュメントのコレクションは購読中のクライアントへと送り出されます。

The onReady callback is called with no arguments when the server has sent all of the initial data for the subscription. The onStop callback is when the subscription is terminated for any reason; it receives a Meteor.Error if the subscription failed due to a server-side error.

onReadyメソッドは、購読の初期化に必要なデータをサーバが送り終えた時に、引数無しで実行されます。onStopメソッドは、何らかの理由で購読が終了した時に実行されます。サーバ側でのエラーなどにより購読に失敗すると、Meteor.Errorを受け取ります。

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

Meteor.subscribeメソッドは戻り値として、購読を制御する以下のメソッドを持ったオブジェクトを返します。

stop()

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

購読を中止します。通常 購読を中止すると、キャッシュから購読のためのデータを削除するよう、サーバからクライアントへ命令が出されます。

ready()

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

購読の準備が整ったとサーバが判断した場合にTrueが返されます。

If you call Meteor.subscribe inside Tracker.autorun, the subscription will be cancelled automatically whenever the computation reruns (so that a new subscription can be created, if appropriate), meaning you don't have to to call stop on subscriptions made from inside Tracker.autorun.

Tracker.autorunメソッドの内部でTracker.autorunメソッドが呼ばれた場合、処理が再実行されるたび自動的に購読は中止されます。(結果的に、新規の購読は適切な手順で作成することができます。)つまり、Tracker.autorunメソッドの内部で生成された購読を停止させるためにstopメソッドを呼び出す必要はないのです。

Environment

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.startup(func)

Run code when a client or a server starts.

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

Arguments

func Function

A function to run on startup.

起動時に実行する関数

On the server, the callback function will run as soon as the server process is finished starting up. On the client, the callback function will run as soon as the page is ready.

サーバ側ではコールバック関数はサーバ起動完了後すぐに実行されます。クライアント側ではコールバック関数はページが準備完了になった後すぐに実行されます。

It's good practice to wrap all code that isn't inside template events, template helpers, Meteor.methods, Meteor.publish, or Meteor.subscribe in Meteor.startup so that your application code isn't executed before the environment is ready.

ひとつのよい方法として、テンプレートイベント、テンプレートヘルパー、Meteor.methodsMeteor.publishMeteor.subscribe以外のすべてのコードをMeteor.startupに入れてしまう方法があります。そうすると、環境が準備される前にコードが実行されてしまうことがなくなります。

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

例えば、サーバ起動時にデータベースが空であれば初期データを作成するためには次のようにします:

if (Meteor.isServer) {
  Meteor.startup(function () {
    if (Rooms.find().count() === 0) {
      Rooms.insert({name: "Initial room"});
    }
  });
}

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

サーバ起動後やクライアント起動後にMeteor.startupを呼び出した場合はコールバック関数はすぐに実行されます。

Packages

All of Meteor's functionality is implemented in modular packages. In addition to the core packages documented above, there are many others that you can add to your app to enable useful functionality.

Meteorの機能のすべては、モジュラーパッケージとして実装されています。上記で説明したコアパッケージに加え、他の多くのパッケージを便利な機能を有効にするために追加することができます。

From the command line, you can add and remove packages with meteor add and meteor remove:

コマンドラインで、meteor addmeteor removeを実行するとパッケージの追加や削除ができます:

# add the less package
meteor add less

# remove the less package
meteor remove less

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

パッケージを追加または削除すると、自動的にアプリがリロードされます。アプリのパッケージは.meteor/packagesの中で追跡されており、あなたと同じ.meteor/packagesファイルを使用しているコラボレーターは、ソースコードをプルした後に自動的にあなたがインストールしたパッケージと同じセットに更新されます。

You can see which packages are used by your app by running meteor list in the app's directory.

アプリディレクトリ内でmeteor listコマンドを実行すると、あなたのアプリがどのパッケージを使用しているか確認できます。

Searching for packages

Currently the best way to search for packages available from the official Meteor package server is Atmosphere, the community package search website maintained by Percolate Studio. You can also search for packages directly using the meteor search command.

Packages that have a : in the name, such as mquandalle:jade, are written and maintained by community members. The prefix before the colon is the name of the user or organization who created that package. Unprefixed packages are maintained by Meteor Development Group as part of the Meteor framework.

パッケージ名はコロン区切りで記載され、コロンの前はパッケージを作成したユーザーです。記載のないものはMeteor Development Groupによりメンテナンスされています。

There are currently over 2000 packages available on Atmosphere. Below is a small selection of some of the most useful packages.

現在Atmosphereには2000以上のパッケージが存在します。あなたにあったものが見つかるでしょう。

accounts-ui

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

accounts-uiはMeteor上のアカウントシステムです。パッケージを追加したあと、テンプレートに{{> loginButtons}}を追加します。accounts-uiはソーシャルログインやログインのための機能を自動的に追加することができます。

See the docs about accounts-ui above..

accounts-uiについてのドキュメントを御覧ください。

coffeescript

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

coffeescriptをMeteorで利用するにはCoffeescriptパッケージを追加してください。.coffeeの拡張子を持つファイルがJavaScriptにコンパイルされるようになります。

email

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

emailを送信するには、Full APIのメール送信の章を御覧ください。

mquandalle:jade

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

jquery

JQuery makes HTML traversal and manipulation, event handling, and animation easy with a simple API that works across most browsers.

JQueryはシンプルなAPIで簡単にDOM操作が可能にします。

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

JQueryは自動的にMeteorアプリに含まれています。詳細はJQueryのドキュメントを御覧ください。

http

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

このパッケージを利用すると、クライアントまたはサーバーからのHTTPリクエストが可能になります。詳細はhttpのドキュメントを御覧ください。

less

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

.less拡張子を持つファイルをコンパイルするために、CSSプリプロセッサのLESSを追加します。Meteorがコンパイルしてもいいファイルには@importを、コンパイルしないファイルには.import.lessを使用してください。

markdown

Include Markdown code in your templates. It's as easy as using the {{# markdown}} helper:

Markdownを使用する場合は、{{# markdown}}をご使用ください。

<div class="my-div">
{{#markdown}}
# My heading

Some paragraph text
{{/markdown}}
</div>

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

Markdownはインデントしないように注意してください。

underscore

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

Underscoreは、配列、オブジェクト、functionを操作するためのコレクションを提供します。MeteorはUnderscoreを利用しているため、Meteorには既にincludeされています。

spiderable

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

このパッケージは、検索エンジンのクローラや他のボットがアプリの内容を参照できるように、アプリケーションのサーバー側のレンダリングを提供します。SEO施策を行う際は、このパッケージをご利用ください。

Check out the Full API Docs

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

MeteorのBasicドキュメントは終了です。より詳しい説明は、Full API Docsを御覧ください。