Goal
既存のMongoDBをMeteor.jsで利用する。Environment
- OS
- Linux version 3.2.0-64-generic (buildd@kissel) (gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5) ) #97-Ubuntu SMP Wed Jun 4 22:04:21 UTC 2014
 
- Meteor.js
- 1.0.3.1
 
- MongoDB
- 2.4.12
 
Procedure
1. 環境変数MONGO_URLをセットする
export MONGO_URL=mongodb://username:password@localhost:27017/dbname
2. ソースコード内にMongoDBを利用するためのコードを入れる
以下のソースコードはデフォルトアプリのコードをベースにしている。
var Test = new Mongo.Collection('test');
if (Meteor.isClient) {
  // counter starts at 0
  Session.setDefault('counter', 0);
  Template.hello.helpers({
    counter: function () {
      return Session.get('counter');
    }
  });
  Template.hello.events({
    'click button': function () {
      // increment the counter when button is clicked
      Session.set('counter', Session.get('counter') + 1);
      console.log(Test.findOne());
    }
  });
}
if (Meteor.isServer) {
  Meteor.startup(function () {
    // code to run on server at startup
    Test.insert({name:"A", age:25});
    Test.insert({name:"B", age:31});
    Test.insert({name:"C", age:22});
    console.log(Test.findOne());
  });
}
コレクションのサイズが小さい場合はこれで完了。
大きい場合は、工夫が必要でそれにはさらに以下のステップを実行する必要がある。
3. autopublish機能を削除する
autopublish機能を削除するとpublish/subscribe機能を利用しないとmongoDBをMeteor.jsで利用できなくなるので注意。
meteor remove autopublish
4. publish/subscribe機能をコードに追加する
var Test = new Mongo.Collection('test');
if (Meteor.isClient) {
  Meteor.subscribe('testdata');
  // counter starts at 0
  Session.setDefault('counter', 0);
  Template.hello.helpers({
    counter: function () {
      return Session.get('counter');
    }
  });
  Template.hello.events({
    'click button': function () {
      // increment the counter when button is clicked
      Session.set('counter', Session.get('counter') + 1);
      console.log(Test.findOne());
    }
  });
}
if (Meteor.isServer) {
  Meteor.startup(function () {
    // code to run on server at startup
    Test.insert({name:"A", age:25});
    Test.insert({name:"B", age:31});
    Test.insert({name:"C", age:22});
    console.log(Test.findOne());
    Meteor.publish('testdata', function() {
      return Test.find({name:"B"});
    });
  });
}
基本的にこのコードの実行結果は上のと同じだが、
クライアントサイドのconsole.logの結果がname:”B”のものになっているところが異なる。
 
    

