node. js Connection & Additions to MongoDB (with async synchronization Process Control)

Source: Internet
Author: User
Tags lua

1. Start the MongoDB database

Download MongoDB database on official website

Create a folder under the MongoDB root directory: Assume that it is named Test.
We think test is a new database for MongoDB.

Create a batch file Xxx.bat with the following contents:

Run the Mongod.exe under the Bin directory under the E-Disk MongoDB folder, with the parameters
-dbpath E:\mongodb\test.

E:\mongodb\bin\mongod.exe -dbpath E:\mongodb\test

This launches the server for MongoDB under the test database.

2. Loading the MongoDB module

Directly npm into the MongoDB module in our node. JS Project

npm install mongodb --save

3. Dependent on the MongoDB module

Add the following dependencies to the JS file where you want to write the logic for adding and deleting MongoDB.

var mongo = require("mongodb");

4. General-Purpose small functions

Write a few general-purpose small functions, and finally create an object, the functions are all hanging onto the object, and finally exports the object out.

/** * Create a database server and develop a database named DatabaseName *@param host IP *@param Port *@param databaseName *@return Open failed return-1, successfully returned to database */function OpenDatabase (host,port,databasename) {The server where the database is createdvar Server =New MONGO. Server (host, port, {auto_reconnect):true});var db =New MONGO. Db (databaseName, server, {safe):true}); Db.open (function (err, db) {if (err) {Console.log (' Failed to open database ');Return-1; }else {Console.log (' Open database Success '); } });return DB;}/** * Connection Data collection *@param DB Database *@param collectionname Data collection name *@return successfully returned collection, the failure returned-1 */function opencollection (db,collectionname) {db.collection (Collectionname,{safe:True},function (errcollection,collection) {if (!errcollection) {Console.log (' Connect data set successfully ');return collection; }else{Console.log (' Connection number set failed ');Return-1; } });}/** * Insert Data *@param collection *@param tmp data to insert *@return successfully returned collection, failed return-1 */function insertcollection (collection,tmp) {var tmp = {username: ' Hello ', password:1}; Collection.insert (Tmp,{safe:True},function (err, result) {if (err) {Console.log (' Incoming data collection failed ' +tmp);Return-1; }else {Console.log (' Insert data set successfully ' +result '; } });return collection;}/** * Query data collection No conditions *@param collection *@return successfully returned a query to the contents of the data collection, the failure returns 1 */function findcollectionnocondition (collection) {Collection.find (). ToArray (function (Errfind,cols) {if (!errfind) {Console.log (' Query data Set Success ' +json.stringify (cols));Return json.stringify (cols); }else {Console.log (' Query data collection failed ');Return-1; } });}/** * Query Data set conditional *@param collection *@return successfully returned a query to the contents of the data collection, the failure returns 1 */function findcollectionhascondition (collection,tmp) {collection.find (TMP). ToArray ( function (Errfind,cols) {if (!errfind) {Console.log (' Query data Set Success ' +json.stringify (cols));Return json.stringify (cols); }else {console.log (' Query data collection failed '); return-1;}});} /** * Delete Data collection * @param collection * @param tmp * @return successfully returned data collection, failed to return-1 */function removecollection (Collec tion,tmp) { //var tmp = {username: ' Hello ', password:1}; Collection.remove (Tmp,{safe:true},function (err, Count) { if (err) {Console.log (' Delete data collection failed ' +tmp); return-1;} else {console.log (' Delete data collection succeeded ' +count); return collection;} });}


5.async module solves the implementation of synchronization logic under node. JS Asynchronous architecture

When I see the super-useful node. JS Code snippet, it says that node. JS is an asynchronous I/O driver, so there's a problem when we run the above functions in sequence: If the previous de function takes a long time, then the function will not wait for the previous function to run, but to run directly. But the result of my previous function is to be used by the latter function.

In this case, serial control flow control under asynchronous I/O is required.

The book describes the Async module, formalities love your third party introduction.

async --save
    • 1

Require in.

var async=require("async");
    • 1

How to use:
Nodejs Async Process Control Async

I'm using waterfall Waterfall mode flow control.
GitHub Waterfall mechanism using demo

And then I was naïve to use it.

 Use the Async waterfall model process to control the connection query that executes the database Async.waterfall ([function(callback) {var db; Db=user.opendatabase ("LocalHost",27017,"Test"); CallbackNULL,DB); },function (db,callback) {var Collection if (Db!=-1) {collection=user.opencollection (Db, ' users '); } callback (null,collection);},  function (collection,callback) { var res; if (Collection!=-1) {res=user.findcollectionnocondition ( collection); Console.log (RES); Callback (null,3);}],function (Err,result) {console.log ( " Async waterfall Model Flow control execution succeeded "+result"; }) 
The result or the second function succeeds before the first function, causing the third function to run incorrectly.

**********************************************************************
First, using the Promise mechanism of module Q to realize synchronization problem of database operation

1.install
npm install q --save
2.require
var Q=require(‘q‘);
3. Rewriting database Crud operation methods
/** * Create a database server and develop a database named DatabaseName *@param host IP *@param Port *@param databaseName *@return Open failed return-1, successfully returned to database */function OpenDatabase (host,port,databasename,collectionname) {The server where the database is createdvar deferred = Q.defer ();var Server =New MONGO. Server (host, port, {auto_reconnect):true});var db =New MONGO. Db (databaseName, server, {safe):true}); Db.open (function (err, db) {if (err) {Console.log (' Failed to open database '); Deferred.reject (ERR); }else {Console.log (' Open database Success '); Deferred.resolve ([db,collectionname]); } });return deferred.promise;}/** * Connection Data collection *@param DB Database *@param collectionname Data collection name *@return successfully returned collection, failed return-1 */function opencollection (db,collectionname) {var deferred = Q.defer (); Db.collection (Collectionname,{safe:True},function (errcollection,collection) {if (!errcollection) {Console.log (' Connect data set successfully '); Deferred.resolve (collection); }else{Console.log (' Connection number set failed '); Deferred.reject (errcollection); } });return deferred.promise;}/** * Insert Data *@param collection *@param tmp data to insert *@return successfully returned collection, failed return-1 */function insertcollection (collection,tmp) {var tmp = {username: ' Hello ', password:1}; Collection.insert (Tmp,{safe:True},function (err, result) {if (err) {Console.log (' Incoming data collection failed ' +tmp);Return-1; }else {Console.log (' Insert data set successfully ' +result '; } });return collection;}/** * Query data collection No conditions *@param collection *@return successfully returned a query to the contents of the data collection, failed to return-1 */function findcollectionnocondition (collection) {var deferred = Q.defer (); Collection.find (). ToArray (function (errfind,cols) {if (!errfind) {Console.log (' Query data Set Success ' +json.stringify (cols)); Deferred.resolve (Json.stringify (cols)); }else {Console.log (' Query data collection failed '); Deferred.reject (Errfind); } });return deferred.promise;}/** * Query Data set conditional *@param collection *@return successfully returned a query to the contents of the data collection, the failure returns 1 */function findcollectionhascondition (collection,tmp) {collection.find (TMP). ToArray ( function (Errfind,cols) {if (!errfind) {Console.log (' Query data Set Success ' +json.stringify (cols));Return json.stringify (cols); }else {console.log (' Query data collection failed '); return-1;}});} /** * Delete Data collection * @param collection * @param tmp * @return successfully returned data collection, failed to return-1 */function removecollection (Collec tion,tmp) { //var tmp = {username: ' Hello ', password:1}; Collection.remove (Tmp,{safe:true},function (err, Count) { if (err) {Console.log (' Delete data collection failed ' +tmp); return-1;} else {console.log (' Delete data collection succeeded ' +count); return collection;} });}

The key points inside are:

    • Defining Defered Objectsvar deferred = Q.defer();
    • Resolve object that defines the successful execution of a functiondeferred.resolve(JSON.stringify(cols));
    • To define the error object for the function to fail successfullydeferred.reject(errfind);
    • Finally, a new promise object is returned toreturn deferred.promise;
4. Chained calls
 User.opendatabase ( "localhost", 27017, "test",  "users". then (function (data) {return user.opencollection (Data[0],data[ 1])}). then (user.findcollectionnocondition). Done (function ' promise execution succeeded ');}, function (err) {Console.log ( Span class= "hljs-string" > "Promise Execution failed:" +err);           

5.log Printing Results
GET/30455.922 MS--Open database successfully connected data collection succeededGet/stylesheets/style.css3046.048 MS--query data collection succeeded [{"_ID":"57731d3a239f75379769ce31","Username":"Liuchen","Password":"12345"},{"_ID":"577328ab5c8d6cf43b3e214d","Username":"Hello","Password":1},{"_ID":"577331F35C8D6CF43B3E214E", "username":  "hello",  "password": Span class= "Hljs-number" >1},{ "_id":  " 57733bf400a7090c35122844 ", " username ": " hello ", " password ": 1},{" _id ":  "57733c0300a7090c35122845",  "username":  "hello",  "password": 1},{ "_id":  "57733c0af8d7813443d51c27", " hello ", " password ": 1}] Promise execution succeeded                
















node. js Connection & Additions to MongoDB (with async synchronization Process Control)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.