forked from soygul/koan
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongo.js
45 lines (37 loc) · 1.32 KB
/
mongo.js
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
'use strict';
/**
* MongoDB configuration using generators (with the help of co-mongo package).
* You can require this config file in your controllers and start using named collections directly.
* See /controllers directory for sample usage.
*/
var mongodb = require('mongodb'),
connect = mongodb.connect,
config = require('./config');
// extending and exposing top co-mongo namespace like this is not optimal but it saves the user from one extra require();
module.exports = mongodb;
/**
* Opens a new connection to the mongo database, closing the existing one if exists.
*/
mongodb.connect = function *() {
if (mongodb.db) {
yield mongodb.db.close();
}
// export mongo db instance
var db = mongodb.db = yield connect(config.mongo.url);
// export default collections
mongodb.counters = db.collection('counters');
mongodb.users = db.collection('users');
mongodb.posts = db.collection('posts');
};
/**
* Retrieves the next sequence number for the given counter (indicated by @counterName).
* Useful for generating sequential integer IDs for certain collections (i.e. user collection).
*/
mongodb.getNextSequence = function *(counterName) {
var results = yield mongodb.counters.findOneAndUpdate(
{_id: counterName},
{$inc: {seq: 1}},
{returnOriginal: false}
);
return results.value.seq
};