-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdbHelper.js
90 lines (71 loc) · 2.11 KB
/
dbHelper.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
const mongoose = require('mongoose');
require('./bookmarkModel'); // register 'bookmark' model
require('dotenv').config();
async function exists(model, URI) {
const found = await model.findById(URI, '_id').exec();
return found ? true : false;
}
async function getBookmarks(model, URI) {
return await model.findById(URI).exec();
}
async function dropBookmarks(model, URI) {
if(!await exists(model, URI)) {
return true;
}
const removed = await model.findByIdAndRemove(URI);
return removed ? true : false;
}
async function addBookmark(model, URI, bookmarkURI) {
if(!await exists(model, URI)) {
const created = model.create({
_id: URI,
bookmarks: [bookmarkURI]
});
if(created) {
return true;
} else {
return false;
}
}
const updatedBookmark = await model.findByIdAndUpdate(URI, {
$push: {
bookmarks: {
$each: [bookmarkURI],
$slice: -1000 // keep only the latest 1000 items
}
}
});
return updatedBookmark ? true : false;
}
async function removeBookmarkItem(model, URI, bookmarkURI) {
if(!await exists(model, URI)) {
return true;
}
const removed = await model.findByIdAndUpdate(URI, {
$pull: {bookmarks: bookmarkURI}
});
return removed ? true : false;
}
async function operationWithModel(operation) {
if(!process.env.MONGODB_URI) {
console.log('Unable to retrieve connection string for MongoDB');
return false;
}
const db = mongoose.createConnection(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false
});
const Bookmarks = db.model('bookmark');
//Bind connection to error event (to get notification of connection errors)
Bookmarks.on('error', console.error.bind(console, 'MongoDB connection error: '));
return operation(Bookmarks);
}
module.exports = {
operationWithModel,
getBookmarks,
dropBookmarks,
addBookmark,
removeBookmarkItem,
exists
}