Tech Tips

  1. プログラミング
  2. 700 view

[Meteor.js][MongoDB][Javascript]別インストールの既存MongoDBを使う方法

meteor

Contents

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());
  });
}
20150303_meteor_monog1
20150303_meteor_monog2
これで実行すると以下のような感じになる。

コレクションのサイズが小さい場合はこれで完了。
大きい場合は、工夫が必要でそれにはさらに以下のステップを実行する必要がある。

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"});
    });
  });
}
publish時のfindの条件指定により、クライアントと同期させるデータのサイズを調整できる。
基本的にこのコードの実行結果は上のと同じだが、
クライアントサイドのconsole.logの結果がname:”B”のものになっているところが異なる。

プログラミングの最近記事

  1. PlatformIO IDE for VSCode を使用して VSCode で Ardu…

  2. ROS Docker イメージで発生した GPG error の解消方法

  3. Streamlit で訪れた国を色づけした世界地図を作成できるアプリケーションを作成してみ…

  4. M5Stack Core2 for AWS – ESP32 IoT開発キットで…

  5. D3.js v7 で点・線・テキスト・ツールチップ・ズームを設定する方法

関連記事

PAGE TOP