Node.js的DAO层,关于数据库操作的db.js


var MongcClient = require( 'mongodb' ).MongoClient;
var express = require( "express" );
var app = express ();
var assert = require( "assert" );

function _connectDB (callback){
var url = 'mongodb://localhost:27017/test' ;
//连接数据库
MongcClient . connect ( url , function (err,db) {
callback(err,db);

})
};

//插入数据
exports . insertOne = function (collectionName,json,callback){
_connectDB ( function (err,db){
db. collection (collectionName). insertOne (json, function (err,result) {
callback(err,result);
db. close ();
})
});
};
//查找数据
exports . find = function (collectionName,json,args,callback) {
var result =[];
if ( arguments . length != 4 ){
callback( "find函数接收4个参数" , null );
return ;
}
//应该省略的条数
var skipnumber = args. pageamount * args. page || 0 ;
//limit的数量
var limit = args. pageamount ;
_connectDB ( function (err,db) {
var cursor = db. collection (collectionName). find (json).skip( skipnumber ).limit( limit );
cursor .each( function (err,doc) {
assert .equal(err, null );
if (err){
callback(err, null );
return ;
}
if (doc != null ){
result . push (doc); //放入结果数组

} else {
//遍历结束,没有更多的文档了
callback( null , result );
}
})
})
};
//删除
exports . deleteMany = function (collectionName,json,callback) {
_connectDB ( function (err, db) {

db. collection (collectionName). deleteMany (
json,
function (err, results) {
callback(err, results);
db. close (); //关闭数据库
}
);
});
};
//修改
exports . updateMany = function (collectionName, json1, json2, callback) {
_connectDB ( function (err, db) {
db. collection (collectionName). updateMany (
json1,
json2,
function (err, results) {
callback(err, results);
db. close ();
});
})
};
//获取留言总数
exports . getAllCount = function (collectionName,callback) {
_connectDB ( function (err, db) {
db. collection (collectionName). count ({}).then( function (count) {
callback(count);
db. close ();
});
})
};

猜你喜欢

转载自blog.csdn.net/weixin_38639882/article/details/79315043
今日推荐