Using Multiple Mongodb Databases with Meteor.js

Update

It is now possible to connect to remote/multiple databases:

var database = new MongoInternals.RemoteCollectionDriver("<mongo url>");
MyCollection = new Mongo.Collection("collection_name", { _driver: database });

Where <mongo_url> is a mongodb url such as mongodb://127.0.0.1:27017/meteor (with the database name)

There is one disadvantage with this at the moment: No Oplog

Old Answer

At the moment this is not possible. Each meteor app is bound to one database.

There are a few ways you can get around this but it may be more complicated that its worth:

One option – Use a separate Meteor App

In your other meteor app (example running at port 6000 on same machine). You can still have reactivity but you need to proxy inserts, removes and updates through a method call

Server:

Cats = Meteor.Collection('cats')

Meteor.publish("cats", function() {
    return Cats.find();
});

Meteor.methods('updateCat, function(id, changes) {
    Cats.update({_id: id}, {$set:changes});
});

Your current Meteor app:

var connection = DDP.connect("http://localhost:6000");

connection.subscribe("cats");
Cats = Meteor.Collection('cats', {connection: connection});

//To update a collection
Cats.call("updateCat", <cat_id>, <changes);

Another option – custom mongodb connection

This uses the node js mongodb native driver.

This is connecting to the database as if you would do in any other node js app.

There is no reactivity available and you can’t use the new Meteor.Collection type collections.

var mongodb = Npm.require("mongodb"); //or var mongodb = Meteor.require("mongodb") //if you use npm package on atmosphere

var db = mongodb.Db;
var mongoclient = mongodb.MongoClient;
var Server = mongodb.Server;

var db_connection = new Db('cats', new Server("127.0.0.1", 27017, {auto_reconnect: false, poolSize: 4}), {w:0, native_parser: false});

db.open(function(err, db) {
    //Connected to db 'cats'

    db.authenticate('<db username>', '<db password>', function(err, result) {
      //Can do queries here
      db.close();
   });
});

Leave a Comment