MongoDB Node.js Connection

Node.js Application Connection to MongoDB

MongoDB is a popular NoSQL databases, which is natively supported by Apiqcloud 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 Apiqcloud Cloud (you can create it at any time) or on any external resources.


In our case, both instances are hosted within a single environment.

2. Connect to your application server via Apiqcloud webSSH.

3. Next, download and install an official MongoDB driver for Node.js

npm install mongodb

In a moment the package will be successfully installed.

4. 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).

?
1
2
3
4
5
6
7
8
var MongoClient = require('mongodb').MongoClient;
// Connect to the db
MongoClient.connect("mongodb://{user}:{password}@{host}:{port}/{database}", 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)


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

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

node script.js


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.

  • MongoDB Node.js Connection
  • 0 A felhasználók hasznosnak találták ezt
Hasznosnak találta ezt a választ?

Kapcsolódó cikkek

Deploy Node.js Project > via Archive / URL

Upload and Deploy Your Node.js Application With Apiqcloud you can easily upload and deploy...

Deploy Node.js Project Via GIT SVN

Deploy Node.js Project via GIT/SVN With Apiqcloudyou can host any public or your private...

Application Connection to MySQL MariaDB

Node.js Application Connection to MySQL MariaDB MySQL and MariaDB are among of the most popular...

How to Connect PostgreSQL with Node.js Application

PostgreSQL is one of the most popular and advanced open-source database solutions. Within...

PHP Accelerators

A PHP accelerator is a PHP extension designed to improve the performance of software applications...