Node.js Application Connection to MongoDB
Node.js Application Connection to MongoDB
This guide shows how to connect a Node.js application server to MongoDB. The workflow covers preparing Node.js and MongoDB servers, connecting through SSH, installing the official MongoDB driver, creating a simple JavaScript connection script, and verifying the connection from the terminal.
Prepare Node.js and MongoDB
You need both a Node.js application server and a MongoDB server. They can be hosted within the platform or on external resources. The source example places both instances inside a single environment.

Connect to the Node.js Server
Open SSH Gate
Connect to the Node.js application server through the platform SSH Gate.

Install the MongoDB Driver for Node.js
Download and install the official MongoDB driver for Node.js:
npm install -s mongodb

Wait for npm to complete the package installation.
Create the MongoDB Connection Script
Create a JavaScript file using any preferred text editor and any filename with a .js extension. The source example uses:
vim script.js
Add the following connection script:
var MongoClient = require('mongodb').MongoClient;
// Connect to the db
MongoClient.connect(
"mongodb://{user}:{password}@{host}:{port}/{database}",
{ useUnifiedTopology: true, useNewUrlParser: true },
function(err, db) {
if (!err) {
console.log("You are connected!");
}
db.close();
}
);
Replace the placeholders in the MongoDB connection string using the information supplied for the MongoDB node:
27017.admin database.The required MongoDB connection data is provided in the email sent for the MongoDB node.

Connection check
If the connection is established successfully, the source script prints You are connected! and then closes the database connection.
Run and Verify the Connection
Run the JavaScript file with Node.js:
node script.js

If all connection values are correct, the terminal displays:
You are connected!
After the connection test succeeds, extend the Node.js code with the MongoDB operations required by the application.
Expected Result
The Node.js application has the official MongoDB driver installed, connects to the specified MongoDB database through the configured connection string, prints the successful connection message, and then closes the database connection.
Important Notes
- Node.js and MongoDB can be hosted within the platform or on external resources.
- The source example hosts both instances in one environment.
- The documented installation command is
npm install -s mongodb. - The source script uses
MongoClient.connect()withuseUnifiedTopologyanduseNewUrlParser. - The documented MongoDB default port is
27017. - MongoDB connection details are provided in the email for the MongoDB node.
- The connection test prints
You are connected!when successful.
