Using mongoskin in Node. js to operate mongoDB instance _ node. js

Source: Internet
Author: User
Tags app service mongodb client
This article mainly introduces how to use mongoskin in Node. js to operate mongoDB instances. Mongous is a lightweight nodejsmongodb driver. For more information, see I. Nonsense

Developed the tourism tag service, Weibo tag retrieval system, map service, and web APP service from March January... use MongoDB scenario from. NET, JAVA environment to node. js platform. The combination of Node. js and mongodb feels better. I feel that mongodb and node. js are born in a pair. Indeed, the mongodb client is the JS parsing engine. Therefore, it is nice to select mongodb and node. js for product prototype. On the Internet, some netizens asked me which driver is the best choice for mongodb development. I used to use the native driver all the time. However, there are many issues to note when writing code, for example, closing a connection... therefore. in the js development environment, I recommend using javasskin.

2. Several concepts to be mentioned

(1) databases: Same as relational databases.
(2) Set: tables in a relational database.
(3) Document: similar to the record of a relational database, it is actually a JSON object.
(4) Database Design: We recommend that you consider NoSQL design and discard the design concept of relational data. In fact, NoSQL database design is profound and requires constant practice in projects.
(5) User System: each database has its own administrator. You can:

The Code is as follows:


Use dbname; db. addUser ('root _ 1', 'test ');


(7) It is recommended to change the external Port
(8) start the service (this is a change in Windows and linux ):

The Code is as follows:


Mongod -- dbpath "XX \ MongoDB \ data \ db" -- logpath "XX \ MongoDB \ log \ mongo. log" -- logappend-auth -- port 7868

3. Build mongodb development infrastructure

(0) npm install strongskin

This section does not introduce Node. js installation, package, and other mechanisms.

(1) Create the configuration file config. json

The Code is as follows:


{
"Dbname": "TEST ",
"Port": "7868 ",
"Host": "127.0.0.1 ",
"Username": "test ",
"Password": "test"
}

(2) create a util related class mongo. js: export a DB object

The Code is as follows:


Var login Skin = require ('login skin '),
Config = require ('./../config. json ');

/*
* @ Des: export the 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 response skin. db (str, option );
})();

(3) construct the basic class of CRUD: To reduce repeated CURD code, you only need to input the relevant JSON object.

The Code is as follows:


Var db = require ('./mongo. js '),
Status = require ('./status '),
Required Skin = require ('your skin ');


Var CRUD = function (collection ){
This. collection = collection;
Db. bind (this. collection );
};

CRUD. prototype = {
/*
* @ Des: Creates a record.
* @ Model: the inserted record. It is a JSON-format model.
* @ Callback: callback. The success or failure information is returned.
*
**/
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 condition. The JSON literal volume queried by Mongo.
* @ Callback: callback, which returns the required record 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: updates a record.
* @ Query: query condition. The JSON literal volume queried by Mongo. The value is _ id.
* @ UpdateModel: JSON-format model to be updated
* @ Callback: the success or failure message is returned.
*
**/
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: deletes a record.
* @ Query: query condition. The JSON literal volume queried by Mongo.
* @ Callback: returns the failed or successful message.
*
**/
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 statuses are required to indicate success and failure, they can be extended to verification code errors, SMS verification errors, username errors, etc.

The Code is as follows:


Module. exports = {
/*
* Successful status
*
**/
Success :{
Status: 1,
Message: 'OK'
},

/*
* Failure status
*
**/
Fail :{
Status: 0,
Message: 'fail'
},

/*
* The two passwords are inconsistent.
**/
RepeatPassword :{
Status: 0,
Message: 'The passwords entered twice are inconsistent'
}
};

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.