準備
1.透過npm指令安裝mongodb
2.安裝mongodb資料庫
CRUD操作
在此之前應對MongoDB資料庫有所了解,知道它的一些增刪指令。
1.增加
var MongoClient = require("mongodb").MongoClient; var DB_URL = "mongodb://localhost:27017/chm"; function insertData(db) { var devices = db.collection('vip'); var data = {"name":"node","age":22,"addr":"nb","addTime":new Date()}; devices.insert(data,function(error, result){ if(error) { console.log('Error:'+ error); }else{ console.log(result.result.n); } db.close(); }); } MongoClient.connect(DB_URL, function(error, db){ console.log('连接成功!'); insertData(db); });
2.查找
var mongodb = require('mongodb') var MongoClient = require('mongodb').MongoClient; var DB_CONN_STR = 'mongodb://localhost:27017/chm'; var selectData = function(db, callback) { //连接到表 var collection = db.collection('vip'); //查询数据 var whereStr = {"name":'node'}; collection.find(whereStr,function(error, cursor){ cursor.each(function(error,doc){ if(doc){ //console.log(doc); if (doc.addTime) { console.log("addTime: "+doc.addTime); } } }); }); } MongoClient.connect(DB_CONN_STR, function(err, db) { console.log("连接成功!"); selectData(db, function(result) { console.log(result); db.close(); }); });
3.更新
var MongoClient = require("mongodb").MongoClient; var DB_URL = "mongodb://localhost:27017/chm"; MongoClient.connect(DB_URL, function(error, db){ console.log("连接成功!"); updateData(db); }); function updateData(db) { var devices = db.collection('vip'); var whereData = {"name":"node"} var updateDat = {$set: {"age":26}}; //如果不用$set,替换整条数据 devices.update(whereData, updateDat, function(error, result){ if (error) { console.log('Error:'+ error); }else{ console.log(result); } db.close(); }); }
4.刪除
var MongoClient = require('mongodb').MongoClient; var DB_URL = "mongodb://localhost:27017/chm"; MongoClient.connect(DB_URL, function(error, db){ console.log("连接成功"); deleteData(db); }); function deleteData(db) { var devices = db.collection('vip'); var data = {"name":"node"}; devices.remove(data, function(error, result){ if (error) { console.log('Error:'+ error); }else{ console.log(result.result.n); } db.close(); }) }
儲存過程
中,透過db.eval(“預存程序ID()”);呼叫預存程序。
在程式碼中呼叫:
var MongoClient = require("mongodb").MongoClient; var DB_URL = "mongodb://localhost:27017/chm"; MongoClient.connect(DB_URL, function(error,db){ console.log("连接成功!"); callProcess(db) }); function callProcess(db) { db.eval("get_vip_count()",function(error, result){ if (error) { console.log(error); }else{ console.log("count:"+result); } db.close(); }); }