-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongo-queries.js
72 lines (65 loc) · 2.21 KB
/
mongo-queries.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
const {DatabaseConnector} = require("./database-connector");
class MongoQueries {
constructor(connectionString, database) {
this.connectionString = connectionString;
this.database = database
}
async execute(operator) {
const connector = new DatabaseConnector(this.connectionString);
const client = await connector.connect();
const db = client.db(this.database);
let result = [];
try {
result = await operator(db);
} catch (err) {
console.error('Error running Mongo query', err);
}
await connector.disconnect();
return result;
}
async find(collection, query) {
const operator = async (db)=> {
const database = db.collection(collection);
return await database.find(query).toArray();
}
return await this.execute(operator);
}
async insertOne(collection, document) {
const operator = async (db)=> {
const database = db.collection(collection);
return await database.insertOne(document);
}
return await this.execute(operator);
}
async updateOne(collection, query, document) {
const operator = async (db)=> {
const database = db.collection(collection);
return await database.updateOne(query, document);
}
return await this.execute(operator);
}
async updateMany(collection, query, document) {
const operator = async (db)=> {
const database = db.collection(collection);
return await database.updateMany(query, document);
}
return await this.execute(operator);
}
async deleteOne(collection, document) {
const operator = async (db)=> {
const database = db.collection(collection);
return await database.deleteOne(document);
}
return await this.execute(operator);
}
async deleteMany(collection, document) {
const operator = async (db)=> {
const database = db.collection(collection);
return await database.deleteMany(document);
}
return await this.execute(operator);
}
}
module.exports = {
MongoQueries
};