[MongoDB Learning Note-02] Two ways node. JS connects MongoDB

Source: Internet
Author: User
Tags install mongodb mongoclient mongodb driver mongodb server

The MongoDB node. JS Driver is officially supported by the native node. JS driver, and he is by far the best implementation and has been supported by MongoDB official. The MONGODB team has adopted the MongoDB node. JS driver as a standard method.

npm install mongodb@1.4.3     // MongoDB Node.js驱动程序npm install mongoose@3.8.8    //mongoose模块

To connect a MongoDB database from node. js, there are two ways to choose:

    1. By instantiating the Mongodbclient class provided in the MongoDB module, and then using the instantiated object to create and manage mongodb connections;
    2. Connect using a string;
1. Connect to MongoDB via client object

Connecting a MongoDB database by instantiating a Mongoclient object is the most common and best way.

To create the syntax for an Mongoclient object instance:

server, options );

Server: a ServerD object;
Options: Database connection option;

As shown, the Mongoclient connection utilizes the server object in the background. The function of this object is to define how the MongoDB driver is connected to the server.

Below, look at an example:

varMongoclient =require(' MongoDB '). Mongoclient, Server =require(' MongoDB '). server;//Create Client Connection objectvarClient =NewMongoclient (NewServer (' localhost ',27017, {socketopations: {connecttimeoutms: -}, Poolsize:5, Auto_reconnect:true}, {numberofretries:3, Retrymilliseconds: -}));//Open a connection to the server-side MongoDB databaseClient.open ( function(err, client) {    if(ERR) {Console.log (' Connection failed! '); }Else{vardb = Client.db (' Blogdb ');//Establish a connection to the database Blogdb        if(DB) {Console.log (' Successful connection '); Db.authenticate (' username ',' pwd ', function(err, result) {   //Authentication of user database identities                if(ERR) {Console.log (' Database user authentication failed '); Client.close ();//Turn off the connection to MongoDBConsole.log (' connection closed ... '); }Else{Console.log (' user authentication through '); Db.logout ( function (err, result) {  //Closes the connection to the database, i.e. exits the database                        if(!err) {Console.log (' exit database error '); } client.close ();//Turn off the connection to MongoDBConsole.log (' Closed connection ... ');                });        }            }); }    }});

Note: To unregister the database, use the logout () method on the Database object. This closes the connection to the database, and you are not able to use the DB object. For example: To db.logout() close a connection to MongoDB, call the Close () method on the client connection, for example: client.close() .

Write Attention

First of all, when we connect to the database, we use a question about the level of write attention, in plain words, personal understanding is equivalent to the problem of a processing priority, you can choose to write to the database whether you need to confirm or not, or if errors are ignored and so on, such as:

Write Level Description
-1 Network errors are ignored
0 Writing confirmation is not necessary.
1 Request Write Confirmation
2 Write acknowledgement requests cross Primary server and one secondary server in replica set
Majority The write acknowledgement is requested from the primary server of the replica set.
The option to create the server object for the Mongoclient connection, as follows:

The database connection options used to create the Mongoclient connection are as follows:

2. Connect to MongoDB via a connection string

This is the way to invoke the Connect () method of the Mongoclient class. Connect uses the following syntax:

MongoClient.connect(connString, options, callback)

The syntax for the connstring string is as follows:

mongodb://username:[email protected]:port/database?opations
mongoclient Connection string components:
Options Description
mongodb:// Specifying a string using MongoDB's connection format
Username The user name to use when validating. Options available
Password The password to use when authenticating. Options available
Host The MongoDB server host name or domain name. It can be multiple host:port combinations to connect multiple MongoDB servers. Example: mongodb://host1:270017, host2://270017, Host3:270017/testdb
Port The port to use when connecting to the MongoDB server. The default value is 27017
Database The name of the database to connect to. Default to Admin
Options The key-value pair for the option used when connecting. You can specify these options on the dbopt and serveropt parameters

Here's an example of connecting to a MONGODB database using the connection string method:

varMongoclient =require(' MongoDB '). Mongoclient; Mongoclient.connect (' Mongodb://mongodb:[email protected]:27017/blogdb ', {db: {w:1, Native_parser:false}, Server: {poolsize:5, socketopations: {connecttimeoutms: -}, Auto_reconnect:true}, Replset: {}, MONGOs: {}}, function(err, db) {                        if(ERR) {Console.log (' Connection failed! '); }Else{Console.log (' connected successfully! ');//Logoff databaseDb.logout ( function(err, result) {                                if(ERR) {Console.log (' logoff failed ... '); } db.close ();//Close connectionConsole.log (' The connection is closed! ');                        }); }});

[MongoDB Learning Note-02] Two ways node. JS connects MongoDB

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: 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.