[注]:这些代码都是基于nodejs进行的.
function mongodbModel(dbname,dataform) {
var MongoClient;
var DB_CONN_STR;
this.init = function() {
MongoClient = require('mongodb').MongoClient;
DB_CONN_STR = 'mongodb://localhost:27017/' + dbname;
}
/*这里是插入数据*/
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);
})
})
}
/*这里是删除数据*/
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;
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('成功删除指定数据');
}
})
/*这里是修改*/
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);
}
})