


Completely master the addition, deletion, modification and query functions of nodejs operating mongodb
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 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 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");
let server = new Server();
let server = new Server({url:"mongodb://localhost:27017/mydb"});
Add method
server.insert(数据表名,需要插入的数据(键值对的对象),回调函数);
Update method
server.update(数据表名,查询的数据(对象),更新的数据(对象),回调函数);
Delete method
server.delete(数据表名,查询的数据(对象),回调函数);
Search method
server.find(数据表名,查询的数据(对象),回调函数);
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); } }); });
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!

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.
