In this video, learn how you can connect to MongoDB from Node.js
- [Instructor] In our example, we will fetch Bitcoin values of the last 30 days from a public API and store it in MongoDB. Then we will find the maximum value and log it out on the console. For that, I have already opened the maxcoin sample project. And as I showed before, the dependencies are defined in package.json; and we have to run NPM install to download those modules into our project. I've already done that when I showed this setup before, so I have this node modules folder here already.
This contains all current dependencies. If you don't have this folder, please run NPM install to install those dependencies. To add MongoDB to the project, there is an official module for communicating with the database; and it can be installed by adding npm install - -save mongodb. And as you see here also in package.json now we have also the dependency to MongoDB in here.
Now let's open test.js and, as you see, we already have the function in here that will fetch the data from the API; and now we have to extend it to first connect to MongoDB. So add const MongoClient equals require MongoDB. That's the module we just installed, and there we want the property MongoClient.
Next we will define a so-called DSN. That's the connection string to the database. So add const DSN equals and in quotes mongodb://localhost:37017/maxcoin.
Next we want to connect to MongoDB, so add MongoClient.connect; and we pass in the DSN is first param, and then we have a callback. Here we use these fat errors again, error and db, and what do we want to do? Obviously, if there was an error, if error, we will throw it; otherwise, we will just let the user know that we have connected successfully to MongoDB server, and then let's also close the database right after that, db.close.
Time for our first test, so I will run node test.js; and let's see if it works. And, as you see, there was this coin desk output; and up here we also have connected successfully to MongoDB's server.
- Basics of relational and nonrelational databases
- Preparing your environment
- When to use document databases
- Inserting data into MongoDB
- Basic insert operations for MongoDB
- Querying data from MongoDB with Node.js
- Using key-value stores
- Using relational databases with Node.js
- Adding MySQL and Sequelize to a project