Meteor database connection - mongodb

I am trying to connect to my Mongo database which is situated on the machine as my Meteor app. Here are two files in my app:
a.js:
if (Meteor.isServer) {
var database = new MongoInternals.RemoteCollectionDriver("mongodb://127.0.0.1:3001/meteor");
Boxes = new Mongo.Collection("boxes", { _driver: database });
Meteor.publish('boxes', function() {
return Boxes.find();
});
}
b.js:
if (Meteor.isClient) {
Meteor.subscribe('boxes');
Template.homeCanvasTpl.helpers({
boxes: function () {
return Boxes.find({});
}
});
}
But I keep getting a "Exception in template helper: ReferenceError: Boxes is not defined" error - any ideas?

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.

Based on feedback from saimeunt in the comments above, s/he pointed out that MongoInternals is unavailable to the client portion of a Meteor app. Therefore, the solution was to add in the line "Boxes = new Mongo.Collection("boxes");" to the client logic - here was the final working solution:
a.js:
if (Meteor.isServer) {
var database = new MongoInternals.RemoteCollectionDriver("mongodb://127.0.0.1:3001/meteor");
Boxes = new Mongo.Collection("boxes", { _driver: database });
Meteor.publish('boxes', function() {
return Boxes.find();
});
}
b.js
if (Meteor.isClient) {
Boxes = new Mongo.Collection("boxes");
Meteor.subscribe('boxes');
Template.homeCanvasTpl.helpers({
boxes: function () {
return Boxes.find({});
}
});
}

Meteor has 2 different environment : the server environment running on Node.JS and the client environment running in browsers.
In your code you declare the Boxes Mongo collection only in the server environment, you need to take this declaration out of the Meteor.isServer condition (and BTW don't use these, separate your code in server/, client/ and lib/ directories).
Also, not sure if you need to connect to your MongoDB this way, maybe you should look into the MONGO_URL environment variable it probably already does what you need ? (provide a mongo connection URL to a distant (or local) Mongo server).

Related

Mongoose : Failed to connect to mongodb instance, but mongo works fine

I'm facing a quite odd issue today.
I have a MongoDB database working just fine on a remote server, say 1.2.3.4, running on port 22222.
When I use the mongo cli to connect via the command line interface, everything works as expected:
mongo --host=1.2.3.4 --port=22222
But when I try to connect to the same instance using mongoose:
var options = {
server: {},
replset: {}
};
options.server.socketOptions = options.replset.socketOptions = { keepAlive: 120 };
mongoose.connect('mongodb://1.2.3.4:22222/test', options);
I get this error:
failed to connect to server [1.2.3.4:22222] on first connect
Anybody knows why?
FYI the all setup is in my company, which happens to have a corporate proxy.
I was thinking that maybe the proxy was the evil one in this case, but then why the mongo cli connection is working just fine?
Do you have a db called test? And have you tried omitting the options?
i.e. mongoose.connect('mongodb://1.2.3.4:22222/test');

Connect to replica set within mongo shell

I'm trying to write a Mongo shell script that connects to two databases, searches for some document(s) in one, and inserts the found document(s) into the other. Kinda like this:
#!/bin/sh
mongo --shell --nodb <<EOF
var db1 = new Mongo( '...' );
var db2 = new Mongo( '...' );
db1.collection.findOne( {...} ).forEach( function( r ) {
db2.collection.save( r )
});
The trick is, both databases are replica sets, and require a username and password.
What is the syntax for using new Mongo() to connect to a replica set and authenticating as a particular user? I tried to use a Mongo URI (http://docs.mongodb.org/manual/reference/connection-string/) but that didn't work.
I don't have a replica set to test this on but I think you can use the Mongo() constructor like this
conn = Mongo("replicasetname/host:port")
from there I think you'll need to get the database manually with
db = conn.getDB("myDatabase")
and then authenticate
db.auth(user, pass)
This could all depend on what shell version you're using as well. I don't see any documentation on using the replica set connection in the latest version so I don't know if it's deprecated or just not mentioned anymore. Hope this helps.

Cannot connect to alternate Mongo DB in Meteor App

I am running a Meteor app. locally using a Virtual Machine (VM). I want to use a new Mongo DB that I have set-up on the VM called 'my_db'. I have set the MONGO_URL on the command line like this:
export MONGO_URL='mongodb://127.0.0.1:3001/my-db'
I have checked that this environment variable is set using echo $MONGO_URL and I get back:
mongodb://127.0.0.1:3001/my-db
However, when I start up my Meteor app. it still connects to the default 'meteor' database. Why is this and what can I do to get it connecting to my alternative 'my_db' database?
Like #dr.dimitr say env vars are only used on the production process (for example connecting your modulus app with the modulus db they provide or another different), on the developing process you can use the mongo drive like this.
if(Meteor.isServer){
Meteor.startup(function () {
var myDatabase = new MongoInternals.RemoteCollectionDriver("<mongo url>");
MyCollection = new Mongo.Collection("collection_name", { _driver: myDatabase });
});
}
Now you need to know name of the url <mongo url> which could be something like mongodb://127.0.0.1:27017/local or meteor
Some Related Posts - (1) and (2)

How to connect meteor and mongoDB on separate machines

I want to connect the Mongo DB on the other server with meteor on my local machine.
Any help appreciated.I am new to meteor.
error on running meteor
Can't start Mongo server. MongoDB had an
unspecified uncaught exception. This can be caused by MongoDB being
unable to write to a local database. Check that you have permissions
to write to .meteor/local. MongoDB does not support filesystems like
NFS that do not allow file locking.
On the meteor app machine, on the server side use this piece of code.
if(Meteor.isServer){
Meteor.startup(function () {
var myDatabase = new MongoInternals.RemoteCollectionDriver("<mongo url>");
MyCollection = new Mongo.Collection("collection_name", { _driver: myDatabasee });
});
}
The only you need to know its the name of the url <mongo url> it could be something like mongodb://127.0.0.1:27017/local or meteor

Meteor does not connect to MongoDB

I'm trying to connect Meteor to an existing MongoDB. I can't duplicate the database or change its name, because is used by other app.
I know I have to set a MONGO_URL environment var to connect with it. However, after I set it, Meteor is not connecting to the especiefied MongoDB database. I tried doing a .find() but it does not return any docs. An .insert() from the web console shows the info in the page, but it doesn't get inserted in the database. Here are the codes:
$ echo $MONGO_URL
mongodb://localhost:27017/autana_dev
./lib/models.js
Posts = new Meteor.Collection('posts');
./server/app.js
Meteor.publish('posts', function() {
return Posts.find();
});
./client/app.js
Meteor.subscribe('posts');
Template.main.posts = function() {
return Posts.find();
};
Any idea? Anyone? My Meteor version release is 0.6.4.1, and the MongoDB version is 2.4.1.
UPDATE: July 28
After running meteor with meteor run, I opened a new console window within project directory to run a meteor mongo console. However, after running meteor mongo I received the following:
mongo: Meteor isn't running.
This command only works while Meteor is running your application
locally. Start your application first.
As you know, because you posted the issue, this is a bug in meteor.
My workaround was to connect to my mongodb with the standard mongo client. You can find what port your db is running on by looking at the file yourapp/.meteor/db/METEOR-PORT and then just run mongo localhost:[put that port number here] .
Are you sure the problem is that Meteor doesn't connect to the database? You have several pieces here that have to work together. I don't see anything obviously wrong, but I would simplify the code to verify the problem is where you think it is.
For example, try adding console.log(Posts.find()) to Meteor.startup on the server.
I am assuming you run Meteor on Linux or Mac. If this is not the case, the code might not work.
the most obvious reason is that the mongo database does not contain any posts documents. What is the output of:
$ mongo
> use autana_dev
> db.posts.find({}).count()
If the output is not null or 0 you might need to connect with a username and password.
export MONGO_URL="mongodb://user:password#localhost:27017/autana_dev
if this does not help, I'd try adding a bit of logging to find out if posts are not sent or not received:
Meteor.publish('posts', function() {
console.log("returning " + Posts.find({}).count() + " posts");
return Posts.find();
});
and if the number is greater than 0 on the client
var postsHandle = Meteor.subscribe('posts');
Template.main.posts = function() {
if( postsHanlde.ready() ){
console.log("I have " + Posts.find({}).count() + " posts on the client");
return Posts.find();
}
};
the condition if( postsHanlde.ready() ) ensures you do not try to show the posts before they have arrived.
If you have documents in your mongodb but nothing gets selected in Meteor, maybe your mongodb is not working correctly.
It is fairly easy to check that by replacing the mongodb with an online solution. Create a free account on mongolab and change your MONGO_URL to the one given by the mongolab console. Insert some posts there and test again.
If you still do not get any documents, then ...
That is all I can think of from your input. Hope it helped.
First, run mongo in one shell's windows
Then simply run "meteor mongo" in another shell's windows while the fist is still running !
On my mac, in the "leaderboard exemple", here is how i've done :
"meteor run leaderboard "
"cd .meteor/leaderboard;meteor mongo "