准备
@H_403_3@1.通过npm命令安装mongodb @H_403_3@
2.安装mongodb数据库,这里不详细介绍了,安装网址:@H_403_3@
CRUD操作
@H_403_3@在此之前应对MongoDB数据库有所了解,知道它的一些增删查改命令。@H_403_3@
{
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,db){
console.log('连接成功!');
insertData(db);
});
2.查找 @H_403_3@
//连接到表
var collection = db.collection('vip');
//查询数据
var whereStr = {"name":'node'};
collection.find(whereStr,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.更新 @H_403_3@
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,result){
if (error) {
console.log('Error:'+ error);
}else{
console.log(result);
}
db.close();
});
}
console.log("连接成功");
deleteData(db);
});
function deleteData(db)
{
var devices = db.collection('vip');
var data = {"name":"node"};
devices.remove(data,result){
if (error) {
console.log('Error:'+ error);
}else{
console.log(result.result.n);
}
db.close();
})
}
存储过程
@H_403_3@在mongodb中创建存储过程 @H_403_3@
所有存储过程都存放在db.system.js中,通过db.eval(“存储过程ID()”);调用存储过程。@H_403_3@
console.log("连接成功!");
callProcess(db)
});
function callProcess(db)
{
db.eval("get_vip_count()",result){
if (error) {
console.log(error);
}else{
console.log("count:"+result);
}
db.close();
});
}