Advanced Node.js Development
上QQ阅读APP看书,第一时间看更新

Running the file in the Terminal

Inside the Terminal, we can run the file using node playground as the directory, with the file itself being mongodb-connect.js:

node playground/mongodb-connect.js

When we run this file, we get Connected to MongoDB server printing to the screen:

If we head over into the tab where we have the MongoDB server, we can see we got a new connection: connection accepted. As you can see in the following screenshot, that connection was closed down, which is fantastic:

Using the Mongo library we were able to connect, print a message, and disconnect from the server.

Now, you might have noticed that we changed the database name in the MongoClient.connect line in Atom, and we never actually did anything to create it. In MongoDB, unlike other database programs, you don't need to create a database before you start using it. If I want to kick up a new database I simply give it a name, something like Users.

Now that I have a Users database, I can connect to it and I can manipulate it. There is no need to create that database first. I'm going to go ahead and change the database name back to TodoApp. If we head into the Robomongo program and connect to our local database, you'll also see that the only database we have is test. The TodoApp database was never even created, even though we connected to it. Mongo is not going to create the database until we start adding data into it. We can go ahead and do that right now.