Nodejs Read From Mongodb and Show on Html

Quick Start Node.js and MongoDB

Use Node.js? Want to learn MongoDB? This is the weblog series for you!

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 piece of work through connecting to a MongoDB database from a Node.js script, retrieving a list of databases, and printing the results to your console.

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

Set upwardly

Before nosotros brainstorm, we demand to ensure y'all've completed a few prerequisite steps.

Install Node.js

Kickoff, brand sure yous 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 xiv.15.4. Run across 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 Commuter

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

If you don't accept the MongoDB Node.js Driver installed, you lot can install information technology with the following command.

          npm install mongodb                  

At the time of writing, this installed version iii.6.4 of the driver. Running npm list mongodb will brandish 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 utilize Atlas, MongoDB's fully-managed database-equally-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 volition be stored. Once your tier is created, load the sample information. 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 Abet Maxime Beugnet.

Become started with an M0 cluster on Atlas today. It'southward gratis forever, and it's the easiest style to try out the steps in this web log serial.

Get your cluster'southward connection info

The final footstep is to prep your cluster for connection.

In Atlas, navigate to your cluster and click CONNECT. The Cluster Connexion Wizard will announced.

The Wizard will prompt you to add your current IP accost to the IP Access Listing and create a MongoDB user if you haven't already done so. Be sure to annotation the username and countersign you use for the new MongoDB user as y'all'll need them in a afterward step.

Next, the Magician volition 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.six or afterward. Copy the provided connectedness string.

For more than details on how to access the Connectedness Sorcerer and complete the steps described above, run into the official documentation.

Connect to your database from a Node.js application

Now that everything is fix, information technology's time to code! Let'due south write a Node.js script that connects to your database and lists the databases in your cluster.

Import MongoClient

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

          const {MongoClient} = crave('mongodb');                  

Create our main function

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.

          async function main() { 	// nosotros'll add lawmaking here presently }                  

The first affair we demand to exercise within of main() is create a constant for our connection URI. The connection URI is the connexion string you copied in Atlas in the previous section. When yous paste the connection cord, don't forget to update <username> and <password> to be the credentials for the user you created in the previous department. The connection string includes a <dbname> placeholder. For these examples, nosotros'll be using the sample_airbnb database, and then replace <dbname> with sample_airbnb.

Note: the username and password you provide in the connectedness string are Not the same equally your Atlas credentials.

          /**  * Connection URI. Update <username>, <password>, and <your-cluster-url> to reflect your cluster.  * See https://docs.mongodb.com/ecosystem/drivers/node/ for more details  */ const uri = "mongodb+srv://<username>:<password>@<your-cluster-url>/examination?retryWrites=true&w=bulk";                  

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

          const client = new MongoClient(uri);                  

Note: When you run this lawmaking, you may run across DeprecationWarnings around the URL cord parserand the Server Discover and Monitoring engine. If you lot encounter these warnings, yous tin remove them past passing options to the MongoClient. For example, you lot could instantiate MongoClient by calling new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }). See the Node.js MongoDB Driver API documentation for more than information on these options.

Now nosotros're set to utilise MongoClient to connect to our cluster. client.connect() will return a promise. We will use the await keyword when nosotros call client.connect() to indicate that we should block further execution until that operation has completed.

          await customer.connect();                  

At present nosotros are fix to collaborate with our database. Let'southward build a part that prints the names of the databases in this cluster. Information technology'south oft useful to comprise this logic in well named functions in order to meliorate the readability of your codebase. Throughout this series, we'll create new functions similar to the office we're creating hither as we learn how to write different types of queries. For now, let's call a function named listDatabases().

          await listDatabases(client);                  

Let's wrap our calls to functions that interact with the database in a effort/grab statement so that nosotros handle any unexpected errors.

          try {     await client.connect();      expect listDatabases(client);   } catch (e) {     panel.error(e); }                  

We desire to be sure we close the connection to our cluster, so we'll end our endeavour/catch with a finally statement.

          finally {     wait customer.close(); }                  

Once we have our main() function written, we demand to telephone call it. Let's send the errors to the console.

          primary().catch(panel.mistake);                  

Putting it all together, our master() office and our call to it will look something similar the post-obit.

          async office chief(){     /**      * Connection URI. Update <username>, <password>, and <your-cluster-url> to reverberate your cluster.      * Come across https://docs.mongodb.com/ecosystem/drivers/node/ for more details      */     const uri = "mongodb+srv://<username>:<password>@<your-cluster-url>/test?retryWrites=truthful&w=majority";        const client = new MongoClient(uri);       endeavor {         // Connect to the MongoDB cluster         wait client.connect();           // Brand the appropriate DB calls         await  listDatabases(client);       } take hold of (e) {         console.error(e);     } finally {         await client.close();     } }  main().catch(console.error);                  

List the databases in our cluster

In the previous section, we referenced the listDatabases() function. Allow'southward implement it!

This function volition remember a list of databases in our cluster and print the results in the console.

          async function listDatabases(client){     databasesList = await client.db().admin().listDatabases();       console.log("Databases:");     databasesList.databases.forEach(db => console.log(` - ${db.name}`)); };                  

Save Your File

You've been implementing a lot of code. Salvage your changes, and proper name your file something like connection.js. To see a copy of the consummate file, visit the nodejs-quickstart GitHub repo.

Execute Your Node.js Script

Now you lot're ready to test your lawmaking! Execute your script by running a command like the following in your terminal: node connexion.js

You will see output like the following:

          Databases:  - sample_airbnb  - sample_geospatial  - sample_mflix  - sample_supplies  - sample_training  - sample_weatherdata  - admin  - local                  

What'due south side by side?

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

At present that you're continued to your database, continue on to the side by side mail in this serial where you'll learn to execute each of the Grime (create, read, update, and delete) operations.

In the concurrently, check out the following resource:

  • Official MongoDB Documentation on the MongoDB Node.js Driver

  • MongoDB University Free Course: M220JS: MongoDB for Javascript Developers

Questions? Comments? We'd dear to connect with y'all. Join the conversation on the MongoDB Community Forums.

All posts in the Quick Get-go: Node.js and MongoDB series:

  • How to connect to a MongoDB database using Node.js (this post)
  • MongoDB and Node.js - CRUD Operations
  • How to analyze your data using MongoDB's Aggregation Framework and Node.js
  • How to implement transactions using Node.js
  • How to react to database changes with modify streams and triggers

Go Started with MongoDB Atlas

Run MongoDB with Node.js using MongoDB Atlas. Start complimentary. No credit card required.

Nodejs Read From Mongodb and Show on Html

Source: https://www.mongodb.com/blog/post/quick-start-nodejs-mongodb-how-to-get-connected-to-your-database

0 Response to "Nodejs Read From Mongodb and Show on Html"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel