Based on node. JS Platform MongoDB Development--mongoskin (by Vczero)

Source: Internet
Author: User

One, nonsensefrom January 13 to the development of MongoDB, the development of tourism labeling services, micro-blog Tag search system, Map services, web App services ... A scenario using MongoDB was transferred from the. NET, Java environment to the node. JS platform. The more you find that node. js and MongoDB feel good. It feels like MongoDB and node. js are a natural pair. Indeed, the client of MongoDB is the parsing engine of JS. Therefore, it is also nice to choose MongoDB and node. js for product prototypes. Online, met netizens asked MongoDB development, choose which driver best, has always been the use of native driver, but write up code there are a lot to note, such as the closing operation of the connection and so on ... Therefore, I recommend the use of Mongoskin in the node. JS development environment. Ii. A few concepts to be said(1) database: Same as relational database. (2) Collection: A table in a relational database. (3) Document: The record of the analogy relational database is actually a JSON object. (4) Database design: Consider NoSQL design, discard relational data design idea; in fact, the design of NoSQL database is profound and need to be practiced continuously in the project. (5) User system: Each database has its own administrator, you can use dbname; Db.adduser (' root_1 ', ' test ');(7) We recommend changing the external port(8) Start the service (this is under Win, Linux slightly modified): mongod--dbpath "xx\mongodb\data\db"--logpath "Xx\mongodb\log\mongo.log"--logappend-auth--port 7868 Iii. Building MongoDB infrastructure for development(0) npm install Mongoskin installation MongoskinThe installation, package, and other mechanisms of node. JS are not described here. (1) Create configuration file Config.json  
{    "dbname": "Test",    "port": "7868", "    Host": "127.0.0.1",    "username": "Test",    "password": "Test" }
(2) Creating Util related classes Mongo.js: Exporting a DB object
1 varMongoskin = require (' Mongoskin ')),2Config = require ('./... /config.json ');3 4 /*5 * @des: Export database connection Module6  * */7Module.exports = (function(){8     varHost =Config.host,9Port =Config.port,TenDbName =Config.dbname, OneUserName =Config.username, APassword =Config.password, -str = ' mongodb://' + userName + ': ' + password + ' @ ' + host + ': ' + port+ '/' +DbName; -  the     varoption = { -Native_parser:true -     }; -  +     returnmongoskin.db (str, option); -})();

(3) Building a crud base class: To reduce duplicate curd code, you only need to pass in the relevant JSON object to

vardb = require ('./mongo.js ')), Status= require ('./status ')), Mongoskin= Require (' Mongoskin ');varCRUD =function(collection) { This. Collection =collection; Db.bind ( This. collection);}; Crud.prototype= {    /** @des: Create a record * @model: Inserted record, JSON-formatted model * @callback: Callback, return insert successful record or failure message * **/Create:function(model, callback) {db[ This. Collection].save (model,function(Err, item) {if(err) {returncallback (Status.fail); } item.status=Status.success.status; Item.message=Status.success.message; returncallback (item);    }); },    /** @des: Read a record * @query: query criteria, JSON literal for MONGO query * @callback: Callback, return a compliant record or failure message * **/read:function(query, callback) {db[ This. Collection].find (query). ToArray (function(err, items) {if(err) {returncallback (Status.fail); }            varobj ={status:status.success.status, message:status.success.message, items:            Items}; returncallback (obj);    }); },    /** @des: Update a record * @query: query criteria, JSON literal for MONGO query, _ID * @updateModel: Model with JSON format to update * @callback: Return success or failure information *    * */Update:function(query, Updatemodel, callback) {varSet ={Set:updatemodel}; db[ This. Collection].update (query, set,function(err) {if(err) {returncallback (Status.fail); }Else{                returncallback (status.success);    }        }); },    /** @des: Delete a record * @query: query criteria, JSON literal for MONGO query * @callback: Returns information of failure or success * **/DeleteData:function(query, callback) {db[ This. Collection].remove (Query,function(err) {if(err) {returncallback (Status.fail); }            returncallback (status.success);    }); }};module.exports= CRUD;

(4) Build Status.json, because need some status to indicate success and failure, later can be extended to CAPTCHA error, SMS verification error, user name error, etc.

Module.exports = {    /** Success Status * **/success: {Status:1, message:' OK '    },    /** Failure Status * **/fail: {status:0, message:' FAIL '    },    /** Two input passwords are inconsistent **/Repeatpassword: {status:0, message:' Two input passwords are inconsistent '    } };

Iv. inserting a piece of data using a crud

var user = {    ' Shangui ballad ',    password:  ' SGAGHAHSWJWH (after MD5) 'function  (data) {            if  (data.status) {                return  res.send ( status.success);            }             return res.send (Status.fail);});

Based on node. JS Platform MongoDB Development--mongoskin (by Vczero)

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.