Home Web Front-end JS Tutorial Completely master the addition, deletion, modification and query functions of nodejs operating mongodb

Completely master the addition, deletion, modification and query functions of nodejs operating mongodb

Dec 23, 2017 am 09:11 AM
javascript mongodb nodejs

This article mainly introduces the addition, deletion, modification and query functions of nodejs operating mongodb. It briefly analyzes the installation of the mongodb module and analyzes the related implementation skills of nodejs operating mongodb database for addition, deletion, modification and query in the form of examples. Friends who need it can refer to it. I hope Can help everyone.

Install related modules

If you use this, you need to install the required modules yourself first and enter

in the root directory


npm install mongodb --save
Copy after login

Install the module. After the installation is successful, you can proceed with the following steps.

Introduction of files

The following is the relevant code I wrote, put it in the relevant directory that you can quote, I put it in the root of express Directory


function Mongo(options) {
  this.settings = {
    url: 'mongodb://localhost:27017/jk',
    MongoClient:require('mongodb').MongoClient,
    assert:require('assert')
  };
  for(let i in options){
    this.settings[i] = options[i];
  }
  this._run = function (fun) {
    let that = this;
    let settings = this.settings;
    this.settings.MongoClient.connect(this.settings.url, function (err, db) {
      settings.assert.equal(null, err);
      console.log("Connected correctly to server");
      fun(db, function () {
        db.close();
      });
    });
  };
  this.insert = function (collectionName, data, func) {
    //增加数据
    let insertDocuments = function (db, callback) {
      let collection = db.collection(collectionName);
      collection.insertMany([
        data
      ], function (err, result) {
        if (!err) {
          func(true);
        } else {
          func(false);
        }
        callback(result);
      });
    };
    this._run(insertDocuments);
  };
  this.update = function (collectionName, updateData, data, func) {
    //更新数据
    let updateDocument = function (db, callback) {
      let collection = db.collection(collectionName);
      collection.updateOne(updateData
        , {$set: data}, function (err, result) {
          if (!err) {
            func(true);
          } else {
            func(false);
          }
          callback(result);
        });
    };
    this._run(updateDocument);
  };
  this.delete = function (collectionName, data, func) {
    //删除数据
    let deleteDocument = function (db, callback) {
      let collection = db.collection(collectionName);
      collection.deleteOne(data, function (err, result) {
        if (!err) {
          func(true);
        } else {
          func(false);
        }
        callback(result);
      });
    };
    this._run(deleteDocument);
  };
  this.find = function (collectionName, data, func) {
    //查找数据
    let findDocuments = function (db, callback) {
      // Get the documents collection
      let collection = db.collection(collectionName);
      // Find some documents
      collection.find(data).toArray(function (err, docs) {
        if (!err) {
          func(true,docs);
        }
        else {
          func(false, err);
        }
        callback(docs);
      });
    };
    this._run(findDocuments);
  };
}
module.exports = Mongo;
Copy after login

I saved it to a file named server.js

Use

We first introduce the module when we need to use the page. For example, I introduce it in the routing file index.js:


##

const Server = require("../server.js");
Copy after login

Then we need to instantiate the object, as follows :


let server = new Server();
Copy after login

If you need to configure related information, you can pass in an object configuration during instantiation, and you can configure the database address:


let server = new Server({url:"mongodb://localhost:27017/mydb"});
Copy after login

encapsulates four methods, add, delete, modify and check, respectively


Add method


server.insert(数据表名,需要插入的数据(键值对的对象),回调函数);
Copy after login

Update method


server.update(数据表名,查询的数据(对象),更新的数据(对象),回调函数);
Copy after login

Delete method


server.delete(数据表名,查询的数据(对象),回调函数);
Copy after login

Search method


server.find(数据表名,查询的数据(对象),回调函数);
Copy after login

The callback function will return two values, the first Boolean type, whether the processing is successful, the second value, the search return The number of found items, and others will return the number of successfully processed items (now only one item is processed at a time)

Use case

For example, I If I need to find data in a route, I need this:


server.find("users",{username:"username"},function (bool,data) {
    if(bool){
      console.log("查询到数据为"+data.length+"条");
    }
    else{
      console.log(data);
    }
  });
});
Copy after login
The above code queries the data of the field where username is username in the users table. If successful, the following data will return an array. If an error occurs, the data error will be returned directly.

Related recommendations:

php database add, delete, modify and query methods

AngularJs add, delete, modify and query methods

Implementation of the basic writing method of adding, deleting, modifying and querying MySql in NodeJS

The above is the detailed content of Completely master the addition, deletion, modification and query functions of nodejs operating mongodb. 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