How can you connect to a MongoDB with Meteor?
Scenario A: Use the built-in DB as default
This is much simpler than what you did. When you run meteor
you actually start a DB with the Meteor server, where Meteor listens on port 3000 and the database on port 3001. The Meteor app is already connected to this database at port 3001 and uses a db named meteor
. There is no need whatsoever to fall back to MongoInternals.RemoteCollectionDriver
. Just remove that code and change things to:
Boxes = new Mongo.Collection("boxes"); // use default MongoDB connection
Scenario B: Use a different DB as default
Using the MONGO_URL
environment variable you can set the connection string to a MongoDB when starting the Meteor server. Instead of the local port 3001 database or an unauthenticated connection you can specify exactly where and how to connect. Start your Meteor server like this:
$ MONGO_URL=mongodb://user:password@localhost:27017/meteor meteor
You can also leave out the user:password@
part of the command if no authentication is needed.
Scenario C: Connect to a second (3rd, etc) DB from the same Meteor app
Now we need to use MongoInternals.RemoteCollectionDriver
. If you wish to use another database that is not the default DB defined upon starting the Meteor server you should use your approach.
var database = new MongoInternals.RemoteCollectionDriver('mongodb://user:password@localhost:27017/meteor');
var numberOfDocs = database.open('boxes').find().count();
Bonus: Why should you not use MongoInternals
with Mongo.Collection
?
As the docs indicate you should not pass any Mongo connection to the new Mongo.Collection()
command, but only a connection to another Meteor instance. That means, if you use DDP.connect
to connect to a different server you can use your code - but you shouldn't mix the MongoInternals
with Mongo.Collection
- they don't work well together.