{
"dbname":"TEST",
"port": "7868",
"host": "127.0.0.1",
"username": "test",
"password": "test"
}
1 var mongoskin = require('mongoskin'), 2 config = require('./../config.json'); 3 4 /* 5 * @des:导出数据库连接模块 6 * */ 7 module.exports = (function(){ 8 var host = config.host, 9 port = config.port, 10 dbName = config.dbname, 11 userName = config.username, 12 password = config.password, 13 str = 'mongodb://' + userName + ':' + password + '@' + host +':' + port+ '/' + dbName; 14 15 var option = { 16 native_parser: true 17 }; 18 19 return mongoskin.db(str, option); 20 })();
(3)构建CRUD的基础类:为了减少重复CURD代码,只需要传入相关的JSON对象即可
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: 创建一条记录 * @model: 插入的记录,JSON格式的model * @callback:回调,返回插入成功的记录或者失败信息 * * */ 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:读取一条记录 * @query:查询条件,Mongo查询的JSON字面量 * @callback:回调,返回符合要求的记录或者失败信息 * * */ 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:更新一条记录 * @query:查询条件,Mongo查询的JSON字面量,此处为_id * @updateModel:需要更新的JSON格式的模型 * @callback:返回成功或者失败信息 * * */ 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:删除一条记录 * @query:查询条件,Mongo查询的JSON字面量 * @callback:返回失败或者成功的信息 * * */ 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)构建status.json,因为需要一些状态表示成功和失败,后期可以拓展为验证码错误、短信验证错误、用户名错误等
module.exports = { /* * 成功状态 * * */ success: { status: 1, message: 'OK' }, /* * 失败状态 * * */ fail: { status: 0, message: 'FAIL' }, /* * 两次输入的密码不一致 * */ repeatPassword: { status: 0, message: '两次输入的密码不一致' } };
四、使用CRUD插入一条数据
var user = { username: '山鬼谣', password: 'sgAGHAHSWJWH(已经md5后)' }; crud.create(user, function(data){ if (data.status) { return res.send(status.success); } return res.send(status.fail); });
%26nbsp;