国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 數(shù)據(jù)庫 > MongoDB > 正文

mongodb操作的模塊手動(dòng)封裝

2020-10-29 18:45:20
字體:
供稿:網(wǎng)友

mongodb操作的模塊手動(dòng)封裝

[注]:這些代碼都是基于nodejs進(jìn)行的.

在nodejs目錄下創(chuàng)建一個(gè)模塊文件*.js,以便調(diào)用,

以下是模塊代碼:

function mongodbModel(dbname,dataform) {  var MongoClient;  var DB_CONN_STR;  this.init = function() {      MongoClient = require('mongodb').MongoClient;      DB_CONN_STR = 'mongodb://localhost:27017/' + dbname;  }  /*這里是插入數(shù)據(jù)*/  this.insert = function(data,callback) {    MongoClient.connect(DB_CONN_STR, function(err, db) {      console.log('連接成功')      var collection = db.collection(dataform);      collection.insert(data, function(err,result){        callback(err,result);      })    })  }  /*這里是刪除數(shù)據(jù)*/  this.remove = function(data,callback){    MongoClient.connect(DB_CONN_STR, function(err, db) {      console.log('連接成功')      var collection = db.collection(dataform);      collection.remove(data, function(err,result){        callback(err,result);      })    })  }  /*這里是修改*/  this.update=function(data,updata,callback){    MongoClient.connect(DB_CONN_STR, function(err, db) {      console.log('連接成功')      var collection = db.collection(dataform);      collection.update(data,updata,function(err,data){        callback(err,data);      })    })  }  /*這里是查詢*/  this.find=function(data,callback){    MongoClient.connect(DB_CONN_STR, function(err, db) {      console.log('連接成功')      var collection = db.collection(dataform);      collection.find(data).toArray(function(err,data){        callback(err,data);      })    })  }}module.exports = mongodbModel;

如何使用:

在同目錄下創(chuàng)建一個(gè)調(diào)用文件*.js

var mongodbModel = require('./mongodbModel');var mongodbObject = new mongodbModel('seraph','singer');mongodbObject.init();/*這里是插入*/mongodbObject.insert({name:'啊xx'},function(err,data){  if(err){    console.log(err);  }else{    console.log(data);  }})/*這是刪除*/mongodbObject.remove({name:'啊xiao'},function(err,data){  if(err){    console.log(err);  }else{    console.log('成功刪除指定數(shù)據(jù)');  }})/*這里是修改*/mongodbObject.update({name:'小李'},{$set:{name:'小勇'}},function(err,data){  if(err){    console.log(err);  }else{    console.log(data);  }})/*這里是條件查詢*/mongodbObject.find({name:'李洛克'},function(err,data){  if(err){    console.log(err);  }else{    console.log(data);  }})

相關(guān)參數(shù):

dbname:是指要操作的database;
dataform:是指要操作的數(shù)據(jù)表;
data:表示需要插入或者查詢或者修改的數(shù)據(jù);
updata:表示修改后的數(shù)據(jù);

個(gè)人在封裝的時(shí)候,callback()是個(gè)難點(diǎn)

如有疑問請(qǐng)留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 康平县| 东乡族自治县| 临漳县| 汝南县| 金昌市| 阳东县| 容城县| 古丈县| 甘南县| 贵阳市| 彭泽县| 福安市| 柘城县| 故城县| 永嘉县| 安福县| 郯城县| 南澳县| 应城市| 云梦县| 新河县| 楚雄市| 瓦房店市| 德化县| 阳东县| 五常市| 明溪县| 农安县| 德州市| 从化市| 江安县| 巴青县| 五台县| 台北县| 双桥区| 长沙市| 兴业县| 巴东县| 县级市| 鱼台县| 保山市|