-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.js
More file actions
247 lines (211 loc) · 7.67 KB
/
index.js
File metadata and controls
247 lines (211 loc) · 7.67 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
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
const { MongoClient } = require('mongodb');
const url = GetConvar('mongo_url', 'unset');
const dbName = GetConvar('mongo_database', 'unset');
let db = false;
/**
* `init()` connects to the MongoDB database.
* @returns A promise that resolves to a string.
*/
async function init() {
if (url === 'unset' || dbName === 'unset')
return '[MongoDB]: Unable to establish connection. (Missing database URL or database name)';
const client = new MongoClient(url);
await client.connect();
db = client.db(dbName);
return `[MongoDB]: Connection established (${dbName})`;
}
init()
.then(console.log)
.catch(console.error)
.finally(() => {
emit('onDatabaseIsReady');
});
let MongoDB = {};
/**
* If the database is ready, return true, otherwise return false.
*/
const hasConnection = () => (db ? true : false);
exports('hasConnection', hasConnection);
MongoDB.hasConnection = hasConnection;
/**
* Finds documents in a collection based on the parameters passed in
* @param collection - The name of the collection you want to find documents from.
* @param params - An array of parameters to pass to the find method.
* @returns An array of documents that match the params
* @example find('people', [{name: 'john', birthyear: {$gt: 1980}}])
*/
const find = async (collection, params) => {
if (!hasConnection) return false;
if (typeof params === 'object') params = [...params];
if (!params) {
console.error(
`Invalid or no params used on find. Collection: ${collection}. If you want to find all documents use findAll()`
);
return false;
}
const dbCollection = db.collection(collection);
return validateDocuments(
await dbCollection
.find(...params)
.toArray()
.catch((err) => console.error(err.message))
);
};
exports('find', find);
MongoDB.find = find;
/**
* Find all documents in a collection that match the given parameters and update them with the given
* update parameters
* @param collection - The collection you want to find and update.
* @param params - The parameters to find the documents.
* @param updateParams - The parameters you want to update.
* @param limit - The number of documents to find and update.
* @returns The return value is the result of the updateMany() method.
* @example findAndUpdate('people', [{name: 'john', deleted: false}], {deleted: true}, 50)
*/
const findAndUpdate = async (collection, params, updateParams, limit) => {
if (!hasConnection) return false;
if (typeof params === 'object') params = [...params];
if (!params) {
console.error(
`Invalid or no params used on find. Collection: ${collection}. If you want to find all documents use findAll()`
);
return false;
}
const ids = [];
const dbCollection = db.collection(collection);
await dbCollection
.find(...params)
.limit(limit)
.forEach((e) => {
ids.push(e._id);
});
return await dbCollection.updateMany(
{ _id: { $in: ids } },
{ $set: updateParams }
);
};
exports('findAndUpdate', findAndUpdate);
MongoDB.findAndUpdate = findAndUpdate;
/**
* It counts the number of documents in a collection that match the given parameters
* @param collection - The name of the collection you want to query.
* @param params - An object that specifies the query criteria.
* @returns The number of documents in the collection that match the query.
* @example countDocuments('people', [{name: 'john'}])
*/
const countDocuments = async (collection, params) => {
if (!hasConnection) return false;
const dbCollection = db.collection(collection);
return await dbCollection.count(...params);
};
exports('countDocuments', countDocuments);
MongoDB.countDocuments = countDocuments;
/**
* Delete one document from the database
* @param collection - The name of the collection you want to delete from.
* @param params - The parameters to use to find the document to delete.
* @returns {acknowledged, deletedCount}
* @example deleteOne('people', {name: 'john'})
*/
const deleteOne = async (collection, params) => {
if (!hasConnection) return false;
if (!params) {
console.error(
`Invalid or no params used on deleteOne. Collection: ${collection}.`
);
return false;
}
const dbCollection = db.collection(collection);
return await dbCollection.deleteOne(params);
};
exports('deleteOne', deleteOne);
MongoDB.deleteOne = deleteOne;
/**
* Delete many documents from a collection
* @param collection - The name of the collection you want to delete from.
* @param params - The parameters to use to find the documents to delete.
* @returns {acknowledged, deletedCount}
* @example deleteMany('people', {name: 'john'})
*/
const deleteMany = async (collection, params) => {
if (!hasConnection) return false;
if (!params) {
console.error(
`Invalid or no params used on deleteMany. Collection: ${collection}.`
);
return false;
}
const dbCollection = db.collection(collection);
return await dbCollection.deleteMany(params);
};
exports('deleteMany', deleteMany);
MongoDB.deleteMany = deleteMany;
/**
* Inserts one document into a collection
* @param collection - The name of the collection you want to insert into.
* @param params - The parameters to be used in the query.
* @returns {acknowledged, insertedId}
* @example insertOne('people', {name: 'john', birthyear: 2003})
*/
const insertOne = async (collection, params) => {
if (!hasConnection) return false;
if (!params) {
console.error(
`Invalid or no params used on insertOne. Collection: ${collection}. Example: insertOne('collection', {_id: 1})`
);
return false;
}
const dbCollection = db.collection(collection);
return await dbCollection.insertOne(params);
};
exports('insertOne', insertOne);
MongoDB.insertOne = insertOne;
/**
* Inserts many documents into a collection
* @param collection - The name of the collection you want to insert into.
* @param params - An array of objects to insert into the collection.
* @returns An array of the inserted documents.
* @example insertMany('people', [{name: 'john', birthyear: 2003}, {name: 'doe', birthyear: 2003}])
*/
const insertMany = async (collection, params) => {
if (!hasConnection) return false;
if (!params) {
console.error(
`Invalid or no params used on insertMany. Collection: ${collection}.`
);
return false;
}
const dbCollection = db.collection(collection);
return await dbCollection.insertMany(params);
};
exports('insertMany', insertMany);
MongoDB.insertMany = insertMany;
/**
* It takes a collection name and an array of parameters, and returns the result
* updateOne method on the collection with the parameters.
* @param collection - The name of the collection you want to update.
* @param params - paramaters to pass
* @returns The result of the updateOne function.
* @example updateOne('people', [{index: '2004'}, {"$set": {index: '2005'}}])
*/
const updateOne = async (collection, params) => {
if (!hasConnection) return false;
if (!params) {
console.error(`Invalid or no params used on updateOne`);
return false;
}
const dbCollection = db.collection(collection);
return await dbCollection.updateOne(...params);
};
exports('updateOne', updateOne);
MongoDB.updateOne = updateOne;
const validateDocuments = (data) => {
if (!Array.isArray(data)) return data;
return data.map((d) => {
if (d._id && typeof d._id !== 'string') d._id = d._id.toString();
return d;
});
};
module.exports = db;
exports('Load', () => MongoDB);