Connecting to MongoDB and writing data
To connect to our MongoDB database from inside of Node.js, we're going to be using an npm module created by the MongoDB team. It's called node-mongodb-native, but it includes all of the features you'll need to connect to and interact with your database. To get to it, we're going to Google node-mongodb-native:
The GitHub repo, which should be the first link, is the one we want—the node-mongodb-native repository—and if we scroll down, we can take a look at a few important links:
First up we have documentation, and we also have our api-docs; these are going to be critical as we start exploring the features that we have inside of this library. If we scroll down further on this page, we'll find a ton of examples on how to get started. We'll be going through a lot of this stuff in this chapter, but I do want to make you aware of where you can find other resources because the mongodb-native library has a ton of features. There are entire courses dedicated to MongoDB, and they don't even begin to cover everything that's built-in to this library.
We're going to be focusing on the important and common subset of MongoDB that we need for Node.js apps. To get started, let's go ahead and open up the documentations, which are shown in the preceding image. When you go to the docs page, you have to pick your version. We'll be using version 3.0 of the driver, and there's two important links:
- The Reference link: This includes guide-like articles, things to get you started, and other various references.
- The API link: This includes the details of every single method available to you when you're working with the library. We'll be exploring some of the methods on this link as we start creating our Node Todo API.
For now though, we can get started by creating a new directory for this project, and then we're going to go ahead and install the MongoDB library and connect to the database we have running. I am going to assume that you have your database running for all the sections in this chapter. I have it running in a separate tab in my Terminal.
If you're on Windows, refer to the instructions in the Windows installation section to start your database if you forget. If you're on a Linux or macOS operating system, use the instructions I have already mentioned, and don't forget to also include that dbpath argument, which is essential for booting up your MongoDB server.