プログラミング + アカデミック + 何か面白いこと

  1. Programming
  2. 0 view

[Meteor.js][MongoDB][Javascript]How to use existing MongoDB

Pocket

meteor

Goal

Use existing MongoDB collection in Meteor.js app.

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. Set MONGO_URL env variable

export MONGO_URL=mongodb://username:password@localhost:27017/dbname

2. Update source code

Following code is based on sample app code.

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

Result is following.
20150303_meteor_monog1
20150303_meteor_monog2

When the collection size is small, step 1 and 2 are enough.
But we need to do one more thing when it’s not.

3. Remove autopublish function

This step removes autopublish function.
After this, we need to use publish/subscribe function when we use mongoDB in meteor app.

meteor remove autopublish

4. Add publish/subscribe part to code

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"});
    });
  });
}

You can restrict published data amount.
This code’s result is almost same as above.
Only one difference is client side console.log result is name:”B” record.

Pocket

Programming recent post

  1. Install sbt 1.0.0 and run sample template

  2. [Machine Learning]Created docker image includ…

  3. [Node.js]How to write batch script with Node.…

  4. [Play][Scala]Develop Request Driven Batch Usi…

  5. [OpenCV][Ruby]Auto check web page design corr…

関連記事

PAGE TOP