确定封装所需参数
1、type =》操作类型
2、collection =》操作的集合
3、data =》操作的数据
4、callback =》操作完成后的回调
var mongodb = require("mongodb");
var MongoClient = mongodb.MongoClient;
var url = "mongodb://127.0.0.1:27017";
var dbname = "myfirstdb"; //数据库名称
var insert = function(collection,data,callback,client){
collection.insert(data,function(err,result){
if (err) {
console.log(err);
}else{
console.log("插入成功");
callback(result.result);
}
client.close();
})
}
var updateOne = function(collection,data,callback,client){
collection.updateOne(data[0],data[1],function(err,result){
if (err) {
console.log(err);
}else{
console.log("更新成功");
callback(result.result);
}
client.close();
})
}
var deleteOne = function(collection,data,callback,client){
collection.deleteOne(data,function(err,result){
if (err) {
console.log(err);
}else{
console.log("删除成功");
callback(result.result);
}
client.close();
})
}
var find = function(collection,data,callback,client){
collection.find(data).toArray(function(err,result){
if (err) {
console.log(err);
}else{
console.log("查询成功");
callback(result);
client.close();
}
})
}
var methodtype = {
insert:insert,
updateOne:updateOne,
deleteOne:deleteOne,
find:find
}
var operateData = function(type,collectionname,data,callback){
MongoClient.connect(url,function(err,client){
if (err) {
console.log(err)
}else{
console.log("连接成功");
var db=client.db(dbname);
var collection = db.collection(collectionname);
//【增删改查】
//对象取值方法
methodtype[type](collection,data,callback,client);
}
})
}
module.exports = operateData;
封装完成。
使用方法--在其他js文件中进行如下操作:
//以更新为例
var operatedata = require("./db封装01"); //引入封装好的js
operatedata("updateOne","firstcollection",[{name:"haha",age:222},{$set:{name:"haha2",age:333}}],function(result){
console.log(result);
})
网友评论