-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmongoUtil.js
More file actions
50 lines (45 loc) · 1.27 KB
/
Copy pathmongoUtil.js
File metadata and controls
50 lines (45 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
var MongoClient = require('mongodb').MongoClient;
var format = require('util').format;
var utils = require('./utils');
var MongoDB = function(host, port, database, collection) {
this.host = host;
this.port = port;
this.database = database;
this.collection = collection;
};
module.exports = MongoDB;
MongoDB.prototype.init = function(cb) {
MongoClient.connect(format("mongodb://%s:%s/%s", this.host, this.port, this.database), function(err, db) {
if(!!err) {
utils.invokeCallback(cb, err);
return;
}
cb(err, db);
});
};
MongoDB.prototype.insert = function(msg, cb) {
var self = this;
this.init(function(err, db) {
db.collection(self.collection).insert(msg, function(err, objects) {
if (!!err) {
throw new Error('mongodb insert message error: %j', msg);
return;
}
utils.invokeCallback(cb, err, objects);
db.close();
});
});
};
MongoDB.prototype.findToArray = function(limit, cb) {
var self = this;
this.init(function(err, db) {
db.collection(self.collection).find({}, {'limit': limit, 'sort': [['timestamp', -1]]}).toArray(function(err, objects) {
if (!!err) {
throw new Error('mongodb find message error: %j', err);
return;
}
utils.invokeCallback(cb, err, objects);
db.close();
});
});
};