Home Web Front-end JS Tutorial 2 ways to connect node.js to MongoDB database

2 ways to connect node.js to MongoDB database

Jun 30, 2018 pm 01:57 PM
mongodb nodejs

I have been learning the basic knowledge of mongdb these days, following the footsteps (code) of the online masters to simulate connecting to the mongodb database. The following article summarizes and introduces the two method tutorials for node.js to connect to the MongoDB database. The introduction in the article is very detailed. Friends who need it can refer to it. Let’s take a look together.

Preface

The MongoDB Node.js driver is the officially supported native node.js driver. It is the best so far. implementation, and is officially supported by MongoDB. The MongoDB team has adopted the MongoDB Node.js driver as a standard approach.

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

To connect to the MongoDB database from Node.js we have two methods to choose from:

  • By instantiating the mongodbClient class provided in the mongodb module, and then using this instantiated object to create and manage mongodb connections;

  • Use strings to connect;

1. Connect to MongoDB through the client object

It is most commonly used to connect to the MongoDB database by instantiating a MongoClient object. The best way.

Syntax for creating a MongoClient object instance:

MongoClient( server, options );
Copy after login

server: a serverd object;
options: database Connection options;

#As shown in the figure above, the MongoClient connection uses the background Server object. The function of this object is to define how the MongoDB driver connects to the server.

Below, look at an example:

var MongoClient = require('mongodb').MongoClient, 
 Server  = require('mongodb').server;

// 创建客户端连接对象
var client = new MongoClient( new Server('localhost', 27017, {
           socketOpations: { connectTimeoutMS: 500 },
           poolSize: 5,
           auto_reconnect: true
          }, {
           numberOfRetries: 3,
           retryMilliSeconds: 500
          }));

// 打开对服务器端MongoDB数据库的连接
client.open(function(err, client) {
 if ( err ) {
  console.log('连接失败!');
 } else {
  var db = client.db('blogdb'); // 建立到数据库blogdb的连接
  if ( db ) {
   console.log('连接成功');
   db.authenticate('username', 'pwd', function(err, result) { // 对用户数据库身份进行验证
    if ( err ) {
     console.log('数据库用户身份验证失败');
     client.close(); // 关闭对MongoDB的连接
     console.log('连接已关闭......');
    } else {
     console.log('用户身份验证通过');
     db.logout(function (err, result) { // 关闭对数据库的连接,即退出数据库
      if ( !err ) {
       console.log('退出数据库出错');
      }

      client.close(); // 关闭对MongoDB的连接
      console.log( '已关闭连接......' );
     });
    }
   });
  }
 }
});
Copy after login

Note: To log out of the database, use the logout() method on the database object. This will close the connection to the database and you will no longer be able to use the Db object. 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, from my personal understanding, it is equivalent to A priority order for handling problems. You can choose whether you need to confirm before writing to the database, or whether to ignore an error, etc., as shown below:

Write LevelDescription
-1Network errors ignored
0Write confirmation is unnecessary
1Request write confirmation
2Write acknowledgment requests span the primary server and a secondary server in the replica set
majorityWrite acknowledgment is requested from the primary server in the replica set The

options used to create the Server object for the MongoClient connection are as follows:

The database connection options used to create a MongoClient connection are as follows:

2. Connect to MongoDB through a connection string

This method requires calling the connect( ) method of the MongoClient class. The syntax for connect is as follows:

MongoClient.connect(connString, options, callback)
Copy after login

The syntax for connString string is as follows:

mongodb://username:password@host:port/database?opations
Copy after login

MongoClient connection string component:

OptionsDescription
mongodb://Specify the string to use the mongodb connection format
usernameUsed for verification username. Optional
passwordThe password to use for authentication. Optional
hostMongoDB server host name or domain name. It can be multiple host:port combinations to connect to multiple MongoDB servers. For example: mongodb://host1:270017, host2://270017, host3:270017/testDB
portThe port used to connect to the MongoDB server. The default value is 27017
databaseThe name of the database to be connected. The default is admin
optionsThe key-value pair of options used when connecting. These options can be specified on the dbOpt and serverOpt parameters

下面,看一个使用连接字符串方法连接MongoDB数据库的示例:

var MongoClient = require('mongodb').MongoClient;
MongoClient.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('连接失败!');
      } else {
       console.log('连接成功!');
       // 注销数据库
       db.logout(function(err, result) {
        if ( err ) {
         console.log('注销失败...');
        }

        db.close(); // 关闭连接
        console.log('连接已经关闭!');
       });
      }

});
Copy after login

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

使用Nodejs连接mongodb数据库的实现

node-mysql中防止SQL注入的方法

The above is the detailed content of 2 ways to connect node.js to MongoDB database. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the use of net4.0 What is the use of net4.0 May 10, 2024 am 01:09 AM

.NET 4.0 is used to create a variety of applications and it provides application developers with rich features including: object-oriented programming, flexibility, powerful architecture, cloud computing integration, performance optimization, extensive libraries, security, Scalability, data access, and mobile development support.

How to configure MongoDB automatic expansion on Debian How to configure MongoDB automatic expansion on Debian Apr 02, 2025 am 07:36 AM

This article introduces how to configure MongoDB on Debian system to achieve automatic expansion. The main steps include setting up the MongoDB replica set and disk space monitoring. 1. MongoDB installation First, make sure that MongoDB is installed on the Debian system. Install using the following command: sudoaptupdatesudoaptinstall-ymongodb-org 2. Configuring MongoDB replica set MongoDB replica set ensures high availability and data redundancy, which is the basis for achieving automatic capacity expansion. Start MongoDB service: sudosystemctlstartmongodsudosys

How to ensure high availability of MongoDB on Debian How to ensure high availability of MongoDB on Debian Apr 02, 2025 am 07:21 AM

This article describes how to build a highly available MongoDB database on a Debian system. We will explore multiple ways to ensure data security and services continue to operate. Key strategy: ReplicaSet: ReplicaSet: Use replicasets to achieve data redundancy and automatic failover. When a master node fails, the replica set will automatically elect a new master node to ensure the continuous availability of the service. Data backup and recovery: Regularly use the mongodump command to backup the database and formulate effective recovery strategies to deal with the risk of data loss. Monitoring and Alarms: Deploy monitoring tools (such as Prometheus, Grafana) to monitor the running status of MongoDB in real time, and

Navicat's method to view MongoDB database password Navicat's method to view MongoDB database password Apr 08, 2025 pm 09:39 PM

It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

Use Composer to solve the dilemma of recommendation systems: andres-montanez/recommendations-bundle Use Composer to solve the dilemma of recommendation systems: andres-montanez/recommendations-bundle Apr 18, 2025 am 11:48 AM

When developing an e-commerce website, I encountered a difficult problem: how to provide users with personalized product recommendations. Initially, I tried some simple recommendation algorithms, but the results were not ideal, and user satisfaction was also affected. In order to improve the accuracy and efficiency of the recommendation system, I decided to adopt a more professional solution. Finally, I installed andres-montanez/recommendations-bundle through Composer, which not only solved my problem, but also greatly improved the performance of the recommendation system. You can learn composer through the following address:

How to Get Started with NodeJS – a Handbook for Beginners How to Get Started with NodeJS – a Handbook for Beginners Oct 09, 2024 am 10:44 AM

Node is an environment in which you can run JavaScript code "Outside the web browser". Node be like – "Hey y'all, you give your JS code to me and I'll run it ". It uses Google's V8 Engine to convert the JavaScript code to Machine Code. Since Node runs JavaScript code outside the web browser, this means that it doesn't have access to certain features that are only available in the browser, like the DOM or the window object or even the localStorage.

How to split a recorded blob stream into multiple 5 second WAV files using JavaScript and make sure it plays normally? How to split a recorded blob stream into multiple 5 second WAV files using JavaScript and make sure it plays normally? Apr 04, 2025 pm 02:39 PM

When recording using JavaScript, we encountered a requirement: the recorded blob stream needs to be...

What is the CentOS MongoDB backup strategy? What is the CentOS MongoDB backup strategy? Apr 14, 2025 pm 04:51 PM

Detailed explanation of MongoDB efficient backup strategy under CentOS system This article will introduce in detail the various strategies for implementing MongoDB backup on CentOS system to ensure data security and business continuity. We will cover manual backups, timed backups, automated script backups, and backup methods in Docker container environments, and provide best practices for backup file management. Manual backup: Use the mongodump command to perform manual full backup, for example: mongodump-hlocalhost:27017-u username-p password-d database name-o/backup directory This command will export the data and metadata of the specified database to the specified backup directory.

See all articles