[MongoDB Study Notes-02] Two Methods for connecting Node. js to MongoDB

Source: Internet
Author: User
Tags install mongodb mongoclient mongodb driver mongodb server
MongoDBNode. js driver is officially supported by the native Node. js driver. It is the best implementation so far and has been officially supported by MongoDB. The MongoDB team has adopted the MongoDBNode. js driver as the standard method. Npminstallmongodb@1.4.3MongoDBNode.js driver npminstall

The MongoDB Node. js driver is officially supported by the native Node. js driver. It is the best implementation so far and has been officially supported by MongoDB. The MongoDB team has adopted the MongoDB Node. js driver as the standard method. Npm install mongodb @ 1. 4. 3 // MongoDB Node. js driver npm install

The MongoDB Node. js driver is officially supported by the native Node. js driver. It is the best implementation so far and has been officially supported by MongoDB. The MongoDB team has adopted the MongoDB Node. js driver as the standard method.

Npm install mongodb@1.4.3 // MongoDB Node. js driver npm install mongoose@3.8.8 // mongoose Module

To connect to the MongoDB database from Node. js, we have two options:

  1. Instantiate the mongodbClient class provided in the mongodb module, and then use the instantiated object to create and manage mongodb connections;
  2. Use a string for connection;
1. Connect to MongoDB through a client object

It is the most common and optimal method to connect to the MongoDB database by instantiating an external client object.

Syntax for creating a Consumer Client object instance:

MongoClient( server, options );

Server: A serverd object;
Options: database connection options;

As shown in, the Consumer Client connects to the Server object in the background. This object defines how the MongoDB driver connects to the server.

Here is an example:

Var login client = require ('mongodb '). login client, Server = require ('mongodb '). server; // create a client connection object var client = new clients client (new Server ('localhost', 27017, {socketOpations: {connectTimeoutMS: 500}, poolSize: 5, auto_reconnect: true}, {numberOfRetries: 3, retryMilliSeconds: 500}); // open the connection client to the server-side MongoDB database. open (function (err, client) {if (err) {console. log ('Connection failed! ');} Else {var db = client. db ('blogdb'); // establish a connection to database blogdb if (db) {console. log ('Connection successfully'); db. authenticate ('username', 'pwd', function (err, result) {// verify the user database identity if (err) {console. log ('database user authentication failed'); client. close (); // close the connection console to MongoDB. log ('Connection closed ...... ');} else {console. log ('user authentication passed '); db. logout (function (err, result) {// close the connection to the database, that is, exit the database if (! Err) {console. log ('database logout error');} client. close (); // close the connection console to MongoDB. log ('Connection closed ...... ');});}});}}});

Note: to log out of the database, use the logout () method on the database object. This will close the connection to the database. You cannot use Db objects. For example:db.logout()To close the connection to MongoDB, call the close () method on the client connection, for example:client.close().

Write concern

First of all, when we connect to the database, we will use a question about the write concern level. To put it bluntly, what I understand is equivalent to a processing priority when a problem occurs, you can choose whether to confirm before writing data to the database or ignore errors, for example:

Write level Description
-1 Network Error ignored
0 Write validation is unnecessary
1 Request write confirmation
2 A secondary server that initiates a write validation request across the primary server and replica set
Majority Write validation is requested from the master server of the replica set
The options used to create the Server object connected to the Consumer Client are as follows:

The database connection options used to create an external client connection are as follows:

2. Connect to MongoDB using a connection string

This method calls the connect () method of the Consumer Client class. The connect syntax is as follows:

MongoClient.connect(connString, options, callback)

The connString syntax is as follows:

mongodb://username:password@host:port/database?opations
The Consumer Client connects to the string component:
Item Description
Mongodb :// The specified string uses the connection format of mongodb.
Username The username used for verification. Optional
Password The password used for authentication. Optional
Host The host name or domain name of the MongoDB server. It can be a combination of multiple hosts: ports to connect to multiple MongoDB servers. For example: mongodb: // host1: 270017, host2: // 270017, host3: 270017/testDB
Port The port used to connect to the MongoDB server. The default value is 27017.
Database Name of the database to be connected. Admin by default
Options Key-value pairs of the options used for connection. You can specify these options on the dbOpt and serverOpt parameters.

Next, let's look at an example of using the connection string method to connect to the MongoDB database:

Var login client = require ('mongodb '). publish client; Publish client. connect ('mongodb: // mongodb: test @ localhost: 27017/blogdb', {db: {w: 1, native_parser: false}, server: {poolSize: 5, socketOpations: {connectTimeoutMS: 500}, auto_reconnect: true}, replSet :{}, mongos :{}}, function (err, db) {if (err) {console. log ('Connection failed! ');} Else {console. log ('Connection successful! '); // Log out of the database. logout (function (err, result) {if (err) {console. log ('logout failed... ');} db. close (); // close the connection console. log ('Connection closed! ');});}});

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: info-contact@alibabacloud.com 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.