Home Web Front-end JS Tutorial How to operate mongodb's fill, delete, modify, and query module using nodejs

How to operate mongodb's fill, delete, modify, and query module using nodejs

Jun 14, 2018 am 11:25 AM
mongodb nodejs

Below I will share with you an example of the production and introduction of the nodejs operation mongodb fill, delete, modify and check module. It has a good reference value and I hope it will be helpful to 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 in a file named server.js

Use

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

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

Then you need to instantiate the object, as follows:

let server = new Server();
Copy after login

If you need to configure related Information can be passed in an object configuration when instantiating, and the address of the database can be configured:

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

There are four methods encapsulated in it, add, delete, modify and check, respectively

Add method

##server.insert(data table name, data to be inserted (key-value pair object), callback function);

Update method##server.update(data table name, queried data (object), updated data (object), callback function);

Delete methodserver.delete(data table name, queried data (object), callback function);

Find methodserver.find(data table name, queried data (object), callback function);

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

Use case

For example, 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, data will return an array later. If an error occurs, data error will be returned directly.

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

MySQL changes root password

How to write quality JS code

Related usage of js array reduce

The above is the detailed content of How to operate mongodb's fill, delete, modify, and query module using nodejs. 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