首页 > 数据库技术 > 详细

mongoDB数据库操作工具库

时间:2017-03-05 20:30:46      阅读:277      评论:0      收藏:0      [点我收藏+]
/*
Mongodb的数据库工具类
*/
var client = require(‘mongodb‘).MongoClient;

function MongoUtil() {
this.url="mongodb://localhost:27017/storage";//在本地新建数据库storage,此后插入的数据都在storage中
}

MongoUtil.prototype.connect=function(callback){
var that = this;
// console.log(3);
client.connect(this.url,function(err,db){
// console.log(4);
if(err){
console.dir(err);
}else{
that.db = db;
callback();
}
});
}

MongoUtil.prototype.close = function(){
this.db.close();
}

MongoUtil.prototype.insertDocuments = function(collectionName,docs,callback) {
var that = this;
this.connect(function(){
var collection = that.db.collection(collectionName);
collection.insertMany(docs, function(err,result){
if(err){
console.dir(err);
}else{
callback(result);
}
that.close();
});

});
}

MongoUtil.prototype.insertDocument = function(collectionName,doc,callback) {
var that = this;
this.connect(function(){
var collection = that.db.collection(collectionName);
collection.insertOne(doc, function(err,result){
if(err){
console.dir(err);
}else{
callback(result.insertedCount);
}
that.close();
});
});
}

MongoUtil.prototype.findAllDocuments = function(collectionName, callback) {
var that = this;
this.connect(function(){
var collection = that.db.collection(collectionName); 
collection.find({}).toArray(function(err,result){
if(err){
console.dir(err);
}else{
callback(result);//返回插入的行数
}
that.close();
});
})
}

MongoUtil.prototype.update = function(collectionName,filter,update,callback){
var that = this;
this.connect(function(){
var collection = that.db.collection(collectionName);
collection.updateOne(filter,update,function(err,result){
if(err){
console.dir(err);
}else{
callback(result.insertedCount);//返回插入的行数
}
});
});
}

MongoUtil.prototype.findOne = function(collectionName,query,options,callback){
var that = this;
this.connect(function(){
var collection = that.db.collection(collectionName);
collection.findOne(query,options).then(function(doc){
callback(doc);
});
});
}

module.exports=new MongoUtil();

 

mongoDB数据库操作工具库

原文:http://www.cnblogs.com/cy2525/p/6506420.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!