Home >Web Front-end >JS Tutorial >Using mongoskin to operate mongoDB instances in Node.js_node.js

Using mongoskin to operate mongoDB instances in Node.js_node.js

WBOY
WBOYOriginal
2016-05-16 16:35:101653browse

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:

Copy code 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 under win, slightly modified under Linux):
Copy code The code is as follows:

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

Copy code The code is as follows:

{
"dbname":"TEST",
"port": "7868",
"host": "127.0.0.1",
"username": "test",
"password": "test"
}

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

Copy code The code is as follows:

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

Copy code The code is as follows:

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.

Copy code The code is as follows:

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'
}
};

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn