Home >Web Front-end >JS Tutorial >nodejs connects to mongodb database to implement addition, deletion, modification and query
Preparation
1. Install mongodb through npm command
2. Install mongodb database
CRUD operation
Before this, you should have some understanding of the MongoDB database and some of its add, delete, check and modify commands.
1. Add
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. Find
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. Update
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. Delete
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(); }) }
Stored procedures
Create stored procedures in mongodb
All stored procedures are stored in db.system.js , call the stored procedure through db.eval("stored procedure ID()");
Call in code:
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(); }); }