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.Result is following.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()); }); }
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
You can restrict published data amount.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"}); }); }); }
This code’s result is almost same as above.
Only one difference is client side console.log result is name:”B” record.