MongoDB Database Connection

Source: Internet
Author: User
Tags install mongodb mongodb server

MongoDB Database Connection

1. First we need to install MongoDB in the package, using the command: NPM install MongoDB; After installing the package, we need to refer to the package as follows:

var mongo = require (' MongoDB ');

In node. js, when you need to connect to a MongoDB database, you first need to create a server object that is hosting the MongoDB database, which specifies the server where the MongoDB database you want to connect to resides.

2. Create the server object , such as the following command:

var new MONGO. Server (host, port, [options]);

Parameter host: Is the address of the specified server;
Parameter port: is the port number of the specified server.
The options parameter value is an object that specifies some of the options that the server needs to select, specifically which objects can be used under their own Baidu; Here is a description of the most commonly used parameters;

Auto_reconnect: This property is a Boolean value, and when the property value is true, the connection is automatically rebuilt when an error occurs during the client-server connection, false by default.

3. Create database as DB object;

After the MongoDB server object is created successfully, you need to create a DB object that represents the MongoDB database, creating the following method:

var new MONGO. Db (databaseName, server, [options]);

DatabaseName: This parameter is required to specify the name of the database that needs to be connected;
Server: Used to specify the server on which the database resides.
Options for an object, parameter optional, the specific parameters of their own Baidu, this side of the introduction of some commonly used parameters.

Safe: is a Boolean value that, when the property value is True, uses the GetLastError command to perform the data access operation, which returns the execution result of the access operation, which defaults to false;

4. Database connection

After the DB object is created, you need to perform a link operation of the database using the object's Open method, which uses the following example: (callback);

Callback is a callback function that specifies the callback function that is returned after the database connection operation is performed, and the callback function specifies the following method:

function (err, db) {  }

In this callback function, two parameters are used, the first parameter is the error object thrown when the linked database fails, the second parameter is a DB object, which represents the successful link database, and when the database connection fails, the value of the parameter is null;

5. Close the database

When a database no longer needs to be used, you can use the Close method of the database object to close the database, as shown here:

Db.close ([Forceclose], [callback]);

The Forceclose parameter value is a Boolean value that, when true, forces the database to close, and after the database is closed, no longer open the database with the Open method.
When the parameter value is false and the database is not forced to close, you can use the open method of the database object to open the database.

Callback is a function that specifies the callback function that is returned after the database connection operation is closed. The callback function is specified as follows:

function (ERR) {}

The callback function has a parameter value that represents the Error object that is thrown when the linked database fails.

6. Listen for the Close event of the database
When the database shuts down, the close event of the object that triggers the database can be specified by listening to the close event of the database object and specifying the callback function when the execution of the shutdown database operation finishes
The processing that needs to be performed, the following code:

function (Err, DB) {}

The callback has 2 parameters, the first parameter is the error object that is thrown when the database fails to close, the second parameter value is a successfully closed database object, and the parameter value is NULL when the database fails to close.

Here is a simple demo of the linked database, the code is as follows:

The Package.json code is as follows:

{  "name": "MDB",  "version": "1.0.0",  "description": "",  "main ":" Index.js ",  " Scripts ": {    " test ":" Echo \ "Error:no test specified\" && exit 1 " c12>  },  "author": "",  "license": "ISC",  "dependencies": {    "MongoDB": "^2.2.33"  }}

Create a new app.js under the root of the project, with the following code:

Const MONGO = require (' MongoDB '); Const Server=MONGO. Server;const Db=MONGO. Db;const Server=NewServer (' localhost ', ' 27017 ', {auto_reconnect:true}); Const DB=NewDb (' datadb ', server, {safe:true});d (function(err, db) {if(err) {Throwerr; } Else{Console.log (' Successfully established database connection ');  Db.close (); }});d B.on (' Close ',function(err, db) {if(err) {Throwerr; } Else{Console.log (' Successfully closed database connection '); }});

Then execute node app.js under the project root directory, as shown in:

Note: When you install MongoDB, it must be 2.2.33 version of MongoDB, if we use NPM install MongoDB by default, it will be installed by default ^3.0.10
This version will cause the database connection to fail, as shown in:

MongoDB Database Connection

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.