Wednesday, September 24, 2014

Connecting to MongoDB

Connecting to MongoDB with Mongoose is really easy.

mongoose.connect('mongodb://localhost/my-cool-database');

Suppose you want to poke around your database outside of Mongoose, though. How do you connect? Use mongo, the shell interface.

Basic Connection

This connects to the "test" database on "localhost".

mongo

Another Machine/Database

You can specify a different machine and/or database by specifying the "database address."

# connect to another database (on localhost)
mongo some-other-db

# connect to another machine/database
mongo whatever.com/some-db

Warning

You can connect to a machine without specifying a database, but this is NOT how to do it.

mongo localhost

This will connect you to "localhost" using the database "localhost." If you want to connect without automatically selecting a database, use the --nodb option.

mongo localhost --nodb

From there, you can connect to a database manually.

Change Port

By default, MongoDB runs on port 10027. If you're running on a different port, just include that in the "database address."

mongo whatever.com:12345/some-db

Close Connection

Now you can connect to your MongoDB in a few different ways. Since we haven't covered anything else yet, the final thing you need to learn is how to disconnect. Baby steps, right?

You can close the connection with exit or ctrl + c.


Check out the accompanying Github repo to these posts about MongoDB/Mongoose.

No comments:

Post a Comment