NodeJS-based Promise-based shard skin reads and writes to MongoDB and nodejsmongodb

Source: Internet
Author: User
Tags new set

NodeJS-based Promise-based shard skin reads and writes to MongoDB and nodejsmongodb

Promise is an asynchronous programming code writing method. Like the Async module, Promise can improve code readability and maintainability. Async encapsulation is better than Promise, but the flexibility, especially the thorough CallBack conversion, is worse than Promise. The source code is directly pasted below, and the comments are very detailed:

(1) database connection file: dbConfig

/*** Created by apple on 2014/12/29.*/VarMongoskin= Require ('Your skin');VarDb=Null;VarDbName="YqbChat";/***@ Function *@ ParamCollectionName*@ Returns{SkinCollection | null | *}*/Exports. getCollection =Function(CollectionName ){If(!Db){// Connect to the local mongodb instance and use the account and password to connect to mongoskin. db ('username: password @ Server ip/Database Name        Db=Mongoskin.Db('Mongodb: // 127.0.0.1: 27017 /'+DbName+'? Auto_reconnect = true & poolSize = 3',{NumberOfRetries: 1,RetryMiliSeconds500,Safe:True,Native_parser:True},{SocketOptions:{Timeout: 5000 }});}ReturnDb. Collection (collectionName );};/***@ FunctionClose Database*/Exports. dbClose =Function(){If(!Db){Db. Close ();}};
(2) Model-layer files
/*** Created by apple on 2015/1/17.*//** Chat room Data Structure** // The chat room corresponding to two users is a collection, and a message is a document* @ {SingleChatRoomID}*@ _ IdInformation No.*@ MsgState0-unread 1-read (int type)*@ MsgContentMessage Content*@ MsgSendUser_id of the message sender*@ Create_time **/// Obtain the MongoDB connection instanceVarMoment= Require ('Moment');VarQ= Require ("Q");// Store the chat room configuration setVarSingleChatRoomConfigInstance=Null;// Current time pointVarCurrentDateTime=Moment(). Format ("YYYY-M-D H: m: s");/***@ FunctionSearch for configuration information in the singleChatRoomConfig document based on singleChatRoomID*@ ParamSingleChatRoomID chat room ID*@ ParamIf the callback function is promise, it is null.*@ ParamIf promise exists, the callback is empty.*/Exports. findSingleChatRoomByID =Function(Data ){// Search for the configurations of the corresponding Chat Room Based on singleChatRoomID. If yes, return the configurations of the chat room; otherwise, return false.    If(SingleChatRoomConfigInstance=Null){SingleChatRoomConfigInstance= Data.Db. GetCollection ('Singlechatroomconfig');}VarDeferred =Q. Defer ();Console. Log ("[SingleChatRoomConfig-> findSingleChatRoomByID]: Start to search for configuration data based on the chat room ID! ");// Query    SingleChatRoomConfigInstance. FindOne ({SingleChatRoomID: Data.SingleChatRoomID},Function(Error, result ){If(TypeofData.Promise! =Undefined){If(! Error) {data.Result= Result;// Console. log (data );                Deferred. resolve (data );}Else{Deferred. reject (error );}}Else{Callback (error, data );}// Db. dbClose ();    });ReturnDeferred. promise ;};/***@ FunctionInsert a new set in the chat room configuration set*@ ParamSingleChatRoomID*@ ParamUser_id_1*@ ParamUser_id_2*@ ParamCallback*@ ParamPromise*/Exports. insertSingleChatRoomByID =Function(Data ){// Search for the configurations of the corresponding Chat Room Based on singleChatRoomID. If yes, return the configurations of the chat room; otherwise, return false.    If(SingleChatRoomConfigInstance=Null){SingleChatRoomConfigInstance= Data.Db. GetCollection ('Singlechatroomconfig');}VarDeferred =Q. Defer ();Console. Log ("[SingleChatRoomConfig-> insertSingleChatRoomByID]: Start to insert data! ");// Console. log (data );    SingleChatRoomConfigInstance. Insert ({SingleChatRoomID: Data.SingleChatRoomID,Users: [Data. user_id_1, data. user_id_2],MsgCount: 0,CreateTime:CurrentDateTime },Function(Error, result ){If(TypeofData.Promise! =Undefined){If(! Error) {data.Result= Result; deferred. resolve (data );}Else{Deferred. reject (error );}// Db. dbClose ();            }Else{Callback (error, result );// Db. dbClose ();            }});ReturnDeferred. promise ;};
(3) Test File
/*** Created by apple on 2015/1/17.*/VarSingleRoomConfigModel= Require ('../Singleroomconfigmodel');VarModel= Require ('../Model');VarDb= Require ('../Db/dbconfig');VarQ= Require ("Q");/***@ FunctionTest whether the configuration record of a chat room exists in singleChatRoomConfig. If no record exists, create*@ ParamSingleChatRoomID*//** CallBack functions */FunctionTestFindAndInsertByID_CALLBACK (singleChatRoomID ){// The callback function that executes the query operation    This. FindSingleChatRoomByIDCallBack =Function(Error, result ){Console. Dir ("FindSingleChatRoomByIDCallBack invoked! "+ Result );// If the result is not empty, All unread information is queried.        If(Result! =Null){}Else        // If the result is null, the number of unread messages returned by a new data record is null.        {SingleRoomConfigModel. InsertSingleChatRoomByID (singleChatRoomID, 1, 2,This. InsertSingleChatRoomByIDCallBack );}};// Callback function for executing the insert operation    This. InsertSingleChatRoomByIDCallBack =Function(Error, result ){If(Error! =Null){Console. Log (result );}Else{Console. Error (error );}};SingleRoomConfigModel. FindSingleChatRoomByID (singleChatRoomID,This. FindSingleChatRoomByIDCallBack );}/** Promise functions */FunctionTestFindAndInsertByID_PROMISE (singleChatRoomID ){VarData = {SingleChatRoomID: SingleChatRoomID,Promise:True,Db:Db };SingleRoomConfigModel. FindSingleChatRoomByID (data). then (/***@ FunctionLogic judgment layer. If a chat room exists, information about the chat room is returned; otherwise, information about the chat room is created.*@ ParamResult*/        Function(Data ){VarDeferred =Q. Defer ();If(Data ){// Console. log ("the chatting room exists. output the chatting room configuration! ");                Deferred. resolve (data );}Else{// Console. log ("the chat room does not exist. Create a chat room! ");// Continue to set the next-layer promise call                Deferred. reject (data );}ReturnDeferred. promise ;},Model. ErrorHandler). then (Function(Data ){// Console. log ("the chat room configuration is obtained! ");            VarDeferred =Q. Defer (); deferred. resolve (data );ReturnDeferred. promise ;},SingleRoomConfigModel. InsertSingleChatRoomByID). done (Function(Data ){// Console. log ("testFindAndInsertByID_PROMISE-finished ");// Console. log (data );            Data.Db. DbClose ()},Model. ErrorHandler);} testFindAndInsertByID_PROMISE ("1");

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.