Cách Connect mongodb

In this Quick Start series, I'll walk you through the basics of how to get started using MongoDB with Node.js. In today's post, we'll work through connecting to a MongoDB database from a Node.js script, retrieving a list of databases, and printing the results to your console.

This post uses MongoDB 4.4, MongoDB Node.js Driver 3.6.4, and Node.js 14.15.4.

Click here to see a previous version of this post that uses MongoDB 4.0, MongoDB Node.js Driver 3.3.2, and Node.js 10.16.3.

Prefer to learn by video? I've got ya covered. Check out the video below that covers how to get connected as well as how to perform the CRUD operations.

Before we begin, we need to ensure you've completed a few prerequisite steps.

First, make sure you have a supported version of Node.js installed. The current version of MongoDB Node.js Driver requires Node 4.x or greater. For these examples, I've used Node.js 14.15.4. See the MongoDB Compatability docs for more information on which version of Node.js is required for each version of the Node.js driver.

Install the MongoDB Node.js Driver

The MongoDB Node.js Driver allows you to easily interact with MongoDB databases from within Node.js applications. You'll need the driver in order to connect to your database and execute the queries described in this Quick Start series.

If you don't have the MongoDB Node.js Driver installed, you can install it with the following command.

At the time of writing, this installed version 3.6.4 of the driver. Running npm list mongodb will display the currently installed driver version number. For more details on the driver and installation, see the official documentation.

Create a Free MongoDB Atlas Cluster and Load the Sample Data

Next, you'll need a MongoDB database. The easiest way to get started with MongoDB is to use Atlas, MongoDB's fully-managed database-as-a-service.

Head over to Atlas and create a new cluster in the free tier. At a high level, a cluster is a set of nodes where copies of your database will be stored. Once your tier is created, load the sample data. If you're not familiar with how to create a new cluster and load the sample data, check out this video tutorial from MongoDB Developer Advocate Maxime Beugnet.

Get started with an M0 cluster on Atlas today. It's free forever, and it's the easiest way to try out the steps in this blog series.

Get Your Cluster's Connection Info

The final step is to prep your cluster for connection.

In Atlas, navigate to your cluster and click CONNECT. The Cluster Connection Wizard will appear.

The Wizard will prompt you to add your current IP address to the IP Access List and create a MongoDB user if you haven't already done so. Be sure to note the username and password you use for the new MongoDB user as you'll need them in a later step.

Next, the Wizard will prompt you to choose a connection method. Select Connect Your Application. When the Wizard prompts you to select your driver version, select Node.js and 3.6 or later. Copy the provided connection string.

For more details on how to access the Connection Wizard and complete the steps described above, see the official documentation.

Now that everything is set up, it's time to code! Let's write a Node.js script that connects to your database and lists the databases in your cluster.

The MongoDB module exports MongoClient, and that's what we'll use to connect to a MongoDB database. We can use an instance of MongoClient to connect to a cluster, access the database in that cluster, and close the connection to that cluster.

Let's create an asynchronous function named main[] where we will connect to our MongoDB cluster, call functions that query our database, and disconnect from our cluster.

The first thing we need to do inside of main[] is create a constant for our connection URI. The connection URI is the connection string you copied in Atlas in the previous section. When you paste the connection string, don't forget to update and to be the credentials for the user you created in the previous section. The connection string includes a placeholder. For these examples, we'll be using the sample_airbnb database, so replace with sample_airbnb.

Note: The username and password you provide in the connection string are NOT the same as your Atlas credentials.

Now that we have our URI, we can create an instance of MongoClient.

Note: When you run this code, you may see DeprecationWarnings around the URL string MongoClient0 and the Server Discover and Monitoring engine. If you see these warnings, you can remove them by passing options to the MongoClient. For example, you could instantiate MongoClient by calling MongoClient1. See the Node.js MongoDB Driver API documentation for more information on these options.

Now we're ready to use MongoClient to connect to our cluster. MongoClient2 will return a promise. We will use the await keyword when we call MongoClient2 to indicate that we should block further execution until that operation has completed.

We can now interact with our database. Let's build a function that prints the names of the databases in this cluster. It's often useful to contain this logic in well named functions in order to improve the readability of your codebase. Throughout this series, we'll create new functions similar to the function we're creating here as we learn how to write different types of queries. For now, let's call a function named MongoClient4.

Let's wrap our calls to functions that interact with the database in a MongoClient5 statement so that we handle any unexpected errors.

We want to be sure we close the connection to our cluster, so we'll end our MongoClient5 with a finally statement.

Once we have our main[] function written, we need to call it. Let's send the errors to the console.

Putting it all together, our main[] function and our call to it will look something like the following.

List the Databases in Our Cluster

In the previous section, we referenced the MongoClient4 function. Let's implement it!

This function will retrieve a list of databases in our cluster and print the results in the console.

You've been implementing a lot of code. Save your changes, and name your file something like main[]0. To see a copy of the complete file, visit the nodejs-quickstart GitHub repo.

Execute Your Node.js Script

Now you're ready to test your code! Execute your script by running a command like the following in your terminal: main[]1

You will see output like the following:

Today, you were able to connect to a MongoDB database from a Node.js script, retrieve a list of databases in your cluster, and view the results in your console. Nice!

Now that you're connected to your database, continue on to the next post in this series where you'll learn to execute each of the CRUD [create, read, update, and delete] operations.

Chủ Đề