Tech Tips

  1. Uncategorized
  2. 341 view

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

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());
  });
}
20150303_meteor_monog1
20150303_meteor_monog2
Result is following.

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.

Uncategorized recent post

  1. Run Amazon FreeRTOS on M5Stack Core2 for AWS …

  2. Udacity Self-Driving Car Engineer Nanodegree …

  3. Install sbt 1.0.0 and run sample template

  4. Visualization of Neural Network and its Train…

  5. [Machine Learning]Created docker image includ…

関連記事

PAGE TOP