Skip to content

Instantly share code, notes, and snippets.

@ajaxray
Created May 1, 2017 17:13
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 ajaxray/0881ffe1faed0618976c674d4661e021 to your computer and use it in GitHub Desktop.
Save ajaxray/0881ffe1faed0618976c674d4661e021 to your computer and use it in GitHub Desktop.
Simplest (just connect, create, find, count) MongoDB wrapper.
import {Query} from './query'
let MongoClient = require('mongodb').MongoClient;
let defaultFailure = function (err) { throw err; };
class Mongo {
connected: boolean;
db: any;
constructor(public url: string) {
this.connected = false;
}
connect (withDb?: Function) {
if(! this.connected) {
MongoClient.connect(this.url, (err, db) => {
if(err) throw err;
this.db = db;
this.connected = true;
if(withDb) withDb(this.db)
})
} else {
withDb(this.db)
}
return this;
}
disconnect() {
this.db.close();
this.connected = false;
}
insert(collName: string, document: any, onSuccess: Function, onFailure?: Function) {
let failure = onFailure || defaultFailure;
this.connect(db => {
db.collection(collName).insertOne(document, (err, result) => {
// Result - http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~insertOneWriteOpResult
err && failure(err) || onSuccess(result);
})
})
};
findAll(collName: string, query: Query, withResult: Function) {
this.connect(db => {
let collection = db.collection(collName);
let condition = query.condition || {};
let cursor = collection.find(condition);
if(query.order) cursor.sort(query.order);
if(query.limit) cursor.limit(query.limit);
if(query.offset) cursor.skip(query.offset);
cursor.toArray((err, result) => {
err && defaultFailure(err) || withResult(result);
})
})
}
count(collName: string, query: Query, withResult: Function) {
this.connect(db => {
let collection = db.collection(collName);
let condition = query.condition || {};
collection.count(condition).then(total => withResult(total));
})
}
}
module.exports = Mongo;
export interface Query {
condition?: Object,
order?: Object,
limit?: number
offset?: number
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment