Created
October 26, 2015 12:14
-
-
Save barretlee/61f335a62469c36b77c9 to your computer and use it in GitHub Desktop.
mongo db
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var MongoClient = require('mongodb').MongoClient; | |
var mg = require('../config').mongodb; | |
var DB = function(){ | |
this.url = "mongodb://" + mg['host'] + ":" + mg['port'] + "/" + mg['database']; | |
}; | |
module.exports = new DB; | |
DB.prototype.connect = function(cb){ | |
MongoClient.connect(this.url, function(err, db) { | |
if(err) { | |
console.log(err); | |
} else { | |
cb && cb(db); | |
} | |
}); | |
}; | |
DB.prototype.insert = function(table, obj, cb){ | |
this.connect(function(db){ | |
db.collection(table).insertOne(obj, function(err, data){ | |
if(err) { | |
console.log(err); | |
} else { | |
cb && cb(data); | |
db.close(); | |
} | |
}); | |
}); | |
}; | |
DB.prototype.find = function(table, condition, cb) { | |
this.connect(function(db) { | |
var data = db.collection(table).find(condition); | |
cb && cb(data); | |
db.close(); | |
}); | |
}; | |
DB.prototype.update = function(table, condition, obj){ | |
this.connect(function(db){ | |
db.collection(table).updateOne(condition, obj, function(err, data) { | |
if(err) { | |
console.log(err); | |
} else { | |
cb && cb(data); | |
db.close(); | |
} | |
}); | |
}); | |
}; | |
DB.prototype.remove = function(table, condition) { | |
this.connect(function(db){ | |
db.collection(table).deleteMany(condition, function(err, data) { | |
if(err) { | |
console.log(err); | |
} else { | |
cb && cb(data); | |
db.close(); | |
} | |
}); | |
}); | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment