Using mongoskin to operate mongoDB instances in Node.js_node.js
1. Nonsense
Since January 2013, I have been exposed to mongodb for development and developed travel tag services, Weibo tag retrieval systems, map services, and web APP services... The scenario of using MongoDB has been transferred from .NET and JAVA environments to the node.js platform. . The more I find that the combination of Node.js and mongodb feels very good. It feels like mongodb and node.js are a natural match. Indeed, the client of mongodb is the parsing engine of JS. Therefore, choosing mongodb and node.js for product prototypes is also a very nice choice. On the Internet, I met netizens asking about which driver is best for mongodb development. I have always used the native driver before, but there are many things to pay attention to when writing code, such as the closing operation of the connection, etc... Therefore, in node.js In the development environment, I recommend using mongoskin.
2. Several concepts that need to be discussed
(1) Database: Same as relational database.
(2) Set: Table in a relational database.
(3) Document: Analogous to the records of a relational database, it is actually a JSON object.
(4) Database design: It is recommended to consider NoSQL design and abandon the design ideas of relational data; in fact, NoSQL database design is broad and profound and needs to be continuously practiced in projects.
(5) User system: Each database has its own administrator, who can:
use dbname; db.addUser('root_1' , 'test');
(7) It is recommended to change the external port
(8) Start the service (this is under win, slightly modified under Linux):
mongod --dbpath "XXMongoDBdatadb" --logpath "XXMongoDBlogmongo.log" --logappend -auth --port 7868
3. Build mongodb development infrastructure
(0) npm install mongoskin Install mongoskin
Node.js installation, package and other mechanisms are not introduced here.
(1) Create configuration file config.json
{
"dbname":"TEST",
"port": "7868",
"host": "127.0.0.1",
"username": "test",
"password": "test"
}
(2) Create util related class mongo.js: export a DB object
var mongoskin = require('mongoskin'),
config = require('./../config.json');
/*
* @des: Export database connection module
* */
module.exports = (function(){
var host = config.host,
port = config.port,
dbName = config.dbname,
userName = config.username,
Password = config.password,
str = 'mongodb://' userName ':' password '@' host ':' port '/' dbName;
var option = {
native_parser: true
};
return mongoskin.db(str, option);
})();
(3) Build the basic class of CRUD: In order to reduce repeated CURD code, you only need to pass in the relevant JSON object
var db = require('./mongo.js'),
Status = require('./status'),
mongoskin = require('mongoskin');
var CRUD = function(collection){
This.collection = collection;
db.bind(this.collection);
};
CRUD.prototype = {
/*
* @des: Create a record
* @model: Inserted record, model in JSON format
* @callback: callback, returns successfully inserted records or failure information
*
* */
Create: function(model, callback){
db[this.collection].save(model, function(err, item){
if(err) {
return callback(status.fail);
}
Item.status = status.success.status;
Item.message = status.success.message;
return callback(item);
});
},
/*
* @des: Read a record
* @query: Query conditions, JSON literal for Mongo query
* @callback: callback, returns records that meet the requirements or failure information
*
* */
Read: function(query, callback){
db[this.collection].find(query).toArray(function(err, items){
if(err){
return callback(status.fail);
}
var obj = {
status: status.success.status,
message: status.success.message,
items: items
};
return callback(obj);
});
},
/*
* @des: Update a record
* @query: Query condition, JSON literal of Mongo query, here is _id
* @updateModel: Model in JSON format that needs to be updated
* @callback: Return success or failure information
*
* */
Update: function(query, updateModel, callback){
var set = {set: updateModel};
db[this.collection].update(query, set, function(err){
if(err){
return callback(status.fail);
}else{
return callback(status.success);
}
});
},
/*
* @des: Delete a record
* @query: Query conditions, JSON literal for Mongo query
* @callback: Return failure or success information
*
* */
deleteData: function(query, callback){
db[this.collection].remove(query, function(err){
if(err){
return callback(status.fail);
}
return callback(status.success);
});
}
};
module.exports = CRUD;
(4) Build status.json, because some status is needed to indicate success and failure. It can be expanded to include verification code errors, SMS verification errors, username errors, etc.
module.exports = {
/*
*Success status
*
* */
Success: {
status: 1,
message: 'OK'
},
/*
* Failed status
*
* */
fail: {
status: 0,
message: 'FAIL'
},
/*
* The passwords entered twice are inconsistent
* */
RepeatPassword: {
status: 0,
message: 'The passwords entered twice are inconsistent'
}
};

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











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:

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

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.

GitLab Database Deployment Guide on CentOS System Selecting the right database is a key step in successfully deploying GitLab. GitLab is compatible with a variety of databases, including MySQL, PostgreSQL, and MongoDB. This article will explain in detail how to select and configure these databases. Database selection recommendation MySQL: a widely used relational database management system (RDBMS), with stable performance and suitable for most GitLab deployment scenarios. PostgreSQL: Powerful open source RDBMS, supports complex queries and advanced features, suitable for handling large data sets. MongoDB: Popular NoSQL database, good at handling sea

Encrypting MongoDB database on a Debian system requires following the following steps: Step 1: Install MongoDB First, make sure your Debian system has MongoDB installed. If not, please refer to the official MongoDB document for installation: https://docs.mongodb.com/manual/tutorial/install-mongodb-on-debian/Step 2: Generate the encryption key file Create a file containing the encryption key and set the correct permissions: ddif=/dev/urandomof=/etc/mongodb-keyfilebs=512

To set up a MongoDB user, follow these steps: 1. Connect to the server and create an administrator user. 2. Create a database to grant users access. 3. Use the createUser command to create a user and specify their role and database access rights. 4. Use the getUsers command to check the created user. 5. Optionally set other permissions or grant users permissions to a specific collection.
