-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMongoDB.js
More file actions
111 lines (96 loc) · 3.8 KB
/
MongoDB.js
File metadata and controls
111 lines (96 loc) · 3.8 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
// connect() is idempotent on a connected client
const { MongoClient, ObjectId } = require('mongodb');
let _lastClient = null;
function createDBConnection(connectionString, options = {}) {
if (!connectionString) throw new Error('connectionString is required');
const client = new MongoClient(connectionString, options);
_lastClient = client;
return client;
}
async function connectToDatabase(client, dbName) {
if (!client) throw new Error('client is required');
if (!dbName) throw new Error('dbName is required');
if (typeof client.connect === 'function') {
try {
await client.connect();
} catch (err) {
throw new Error(`Failed to connect client: ${err.message}`);
}
}
_lastClient = client;
return client.db(dbName);
}
async function insertData(client, dbName, collectionName, dataObject) {
if (!dataObject || typeof dataObject !== 'object') throw new Error('dataObject must be an object');
if (!collectionName) throw new Error('collectionName is required');
const db = await connectToDatabase(client, dbName);
const col = db.collection(collectionName);
const doc = Object.assign({}, dataObject, { createdAt: new Date() });
const res = await col.insertOne(doc);
return res;
}
async function getAllDataByCollection(client, dbName, collectionName) {
if (!collectionName) throw new Error('collectionName is required');
const db = await connectToDatabase(client, dbName);
const col = db.collection(collectionName);
const docs = await col.find({}).toArray();
return docs;
}
async function getDataById(client, dbName, collectionName, documentId) {
if (!documentId) throw new Error('documentId is required');
if (!collectionName) throw new Error('collectionName is required');
const db = await connectToDatabase(client, dbName);
const col = db.collection(collectionName);
let queryId = documentId;
try {
queryId = new ObjectId(documentId);
} catch (e) {
// keep original value if it's not a valid ObjectId string
}
const doc = await col.findOne({ _id: queryId });
return doc;
}
async function deleteDataById(client, dbName, collectionName, query) {
if (!query) throw new Error('documentId is required');
if (!collectionName) throw new Error('collectionName is required');
const db = await connectToDatabase(client, dbName);
const col = db.collection(collectionName);
const res = await col.deleteOne(query);
return res;
}
async function deleteManyByQuery(client, dbName, collectionName, query) {
if (!query || typeof query !== 'object') throw new Error('query must be an object');
if (!collectionName) throw new Error('collectionName is required');
const db = await connectToDatabase(client, dbName);
const col = db.collection(collectionName);
const res = await col.deleteMany(query);
return res;
}
async function insertManyDocuments(client, dbName, collectionName, documents) {
if (!Array.isArray(documents) || documents.length === 0) throw new Error('documents must be a non-empty array');
if (!collectionName) throw new Error('collectionName is required');
const db = await connectToDatabase(client, dbName);
const col = db.collection(collectionName);
const docs = documents.map(d => Object.assign({}, d, { createdAt: new Date() }));
const res = await col.insertMany(docs);
return res;
}
async function closeConnection() {
if (_lastClient && typeof _lastClient.close === 'function') {
await _lastClient.close();
_lastClient = null;
return true;
}
return false;
}
module.exports = {
createDBConnection,
connectToDatabase,
insertData,
getAllDataByCollection,
getDataById,
deleteDataById,
deleteManyByQuery,
insertManyDocuments,
closeConnection,
};