Ruk-Com PaaS Documentation

Build, deploy and operate applications on the platform.

RUK-COM PAAS / DATABASES

Node.js Application Connection to MongoDB

This guide is maintained for Ruk-Com PaaS. Screens and options may vary by platform version and account permissions.

Confirm the environment, region and account permissions, and back up current settings before changing a production system.

MongoDB is a popular NoSQL database, which is natively supported by the platform and can be easily installed on the Cloud. Below, we’ll consider a simple example of how to connect this DB stack from your Node.js application server.

  1. In order to follow this guide, you’ll need Node.js and MongoDB servers either within the platform (you can create it at any time) or on any external resources.

Image 31: MongoDB Node.js environment In our case, both instances are hosted within a single environment.

  1. Connect to your application server via SSH Gate.

Image 32: SSH connection to Node.js 3. Next, download and install an official MongoDB driver for Node.js:

bash Copy

npm install -s mongodb

Image 33: install MongoDB driver for Node.js In a moment the package will be successfully installed.

  1. Now, create a file with a script to establish connection with your database. You can use any preferable text editor for this task, as well as any filename with the .js extension (e.g., vim script.js).

js Copy

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();
});

Here, you need to adjust the connection string (all the required information is provided within email for your MongoDB node):

  • {user} - username to log into database with
  • {password} - password for the appropriate user
  • {host} - link to your MongoDB container
  • {port} - port to be used for connection (use the default one - 27017)
  • {database} - database to be accessed (e.g., the default one - admin)

Image 34: MongoDB connection script With this script you can access the specified database server and, if connection is successfully established, see the “You are connected!” phrase.

  1. Let’s run the code, using the appropriate command:

bash Copy

node script.js

Image 35: check Node.js connection to MongoDB If everything is specified correctly, you should see the “You are connected!” string within terminal. Next, you can extend code to execute all of the required actions.