Skip to content

Instantly share code, notes, and snippets.

@barretlee
Created October 26, 2015 12:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barretlee/3376969e7f2777eecab9 to your computer and use it in GitHub Desktop.
Save barretlee/3376969e7f2777eecab9 to your computer and use it in GitHub Desktop.
mongo
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