


How to operate mongodb's fill, delete, modify, and query module using 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 directorynpm install mongodb --save
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;
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");
Then you need to instantiate the object, as follows:
let server = new Server();
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"});
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 caseFor 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); } }); });
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 passwordHow to write quality JS codeRelated usage of js array reduceThe 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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

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

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

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

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:

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.

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

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.
