-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.js
33 lines (26 loc) · 980 Bytes
/
db.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
require('dotenv').config();
const { MongoClient } = require('mongodb');
// Atlas URL - replace UUU with user, PPP with password, XXX with hostname
// const url = 'mongodb+srv://UUU:[email protected]/issuetracker?retryWrites=true';
// mLab URL - replace UUU with user, PPP with password, XXX with hostname
// const url = 'mongodb://UUU:[email protected]:33533/issuetracker';
let db;
async function connectToDb() {
const url = process.env.DB_URL || 'mongodb://localhost/issuetracker';
const client = new MongoClient(url, { useNewUrlParser: true });
await client.connect();
console.log('Connected to MongoDB at', url);
db = client.db();
}
async function getNextSequence(name) {
const result = await db.collection('counters').findOneAndUpdate(
{ _id: name },
{ $inc: { current: 1 } },
{ returnOriginal: false },
);
return result.value.current;
}
function getDb() {
return db;
}
module.exports = { connectToDb, getNextSequence, getDb };