/
MongoDb.node.ts
363 lines (307 loc) · 10.9 KB
/
MongoDb.node.ts
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
import type {
IExecuteFunctions,
ICredentialsDecrypted,
ICredentialTestFunctions,
IDataObject,
INodeCredentialTestResult,
INodeExecutionData,
INodeType,
INodeTypeDescription,
JsonObject,
} from 'n8n-workflow';
import { NodeOperationError } from 'n8n-workflow';
import { nodeDescription } from './MongoDbDescription';
import {
buildParameterizedConnString,
prepareFields,
prepareItems,
validateAndResolveMongoCredentials,
} from './GenericFunctions';
import type {
FindOneAndReplaceOptions,
FindOneAndUpdateOptions,
UpdateOptions,
Sort,
} from 'mongodb';
import { MongoClient, ObjectId } from 'mongodb';
import type { IMongoParametricCredentials } from './mongoDb.types';
export class MongoDb implements INodeType {
description: INodeTypeDescription = nodeDescription;
methods = {
credentialTest: {
async mongoDbCredentialTest(
this: ICredentialTestFunctions,
credential: ICredentialsDecrypted,
): Promise<INodeCredentialTestResult> {
const credentials = credential.data as IDataObject;
try {
const database = ((credentials.database as string) || '').trim();
let connectionString = '';
if (credentials.configurationType === 'connectionString') {
connectionString = ((credentials.connectionString as string) || '').trim();
} else {
connectionString = buildParameterizedConnString(
credentials as unknown as IMongoParametricCredentials,
);
}
const client: MongoClient = await MongoClient.connect(connectionString);
const { databases } = await client.db().admin().listDatabases();
if (!(databases as IDataObject[]).map((db) => db.name).includes(database)) {
// eslint-disable-next-line n8n-nodes-base/node-execute-block-wrong-error-thrown
throw new Error(`Database "${database}" does not exist`);
}
await client.close();
} catch (error) {
return {
status: 'Error',
message: error.message,
};
}
return {
status: 'OK',
message: 'Connection successful!',
};
},
},
};
async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
const { database, connectionString } = validateAndResolveMongoCredentials(
this,
await this.getCredentials('mongoDb'),
);
const client: MongoClient = await MongoClient.connect(connectionString);
const mdb = client.db(database);
const returnItems: INodeExecutionData[] = [];
let responseData: IDataObject | IDataObject[] = [];
const items = this.getInputData();
const operation = this.getNodeParameter('operation', 0);
if (operation === 'aggregate') {
// ----------------------------------
// aggregate
// ----------------------------------
try {
const queryParameter = JSON.parse(this.getNodeParameter('query', 0) as string);
if (queryParameter._id && typeof queryParameter._id === 'string') {
queryParameter._id = new ObjectId(queryParameter._id as string);
}
const query = mdb
.collection(this.getNodeParameter('collection', 0) as string)
.aggregate(queryParameter as Document[]);
responseData = await query.toArray();
} catch (error) {
if (this.continueOnFail()) {
responseData = [{ error: (error as JsonObject).message }];
} else {
throw error;
}
}
} else if (operation === 'delete') {
// ----------------------------------
// delete
// ----------------------------------
try {
const { deletedCount } = await mdb
.collection(this.getNodeParameter('collection', 0) as string)
.deleteMany(JSON.parse(this.getNodeParameter('query', 0) as string) as Document);
responseData = [{ deletedCount }];
} catch (error) {
if (this.continueOnFail()) {
responseData = [{ error: (error as JsonObject).message }];
} else {
throw error;
}
}
} else if (operation === 'find') {
// ----------------------------------
// find
// ----------------------------------
try {
const queryParameter = JSON.parse(this.getNodeParameter('query', 0) as string);
if (queryParameter._id && typeof queryParameter._id === 'string') {
queryParameter._id = new ObjectId(queryParameter._id as string);
}
let query = mdb
.collection(this.getNodeParameter('collection', 0) as string)
.find(queryParameter as Document);
const options = this.getNodeParameter('options', 0);
const limit = options.limit as number;
const skip = options.skip as number;
const sort: Sort = options.sort && JSON.parse(options.sort as string);
if (skip > 0) {
query = query.skip(skip);
}
if (limit > 0) {
query = query.limit(limit);
}
if (sort && Object.keys(sort).length !== 0 && sort.constructor === Object) {
query = query.sort(sort);
}
const queryResult = await query.toArray();
responseData = queryResult;
} catch (error) {
if (this.continueOnFail()) {
responseData = [{ error: (error as JsonObject).message }];
} else {
throw error;
}
}
} else if (operation === 'findOneAndReplace') {
// ----------------------------------
// findOneAndReplace
// ----------------------------------
const fields = prepareFields(this.getNodeParameter('fields', 0) as string);
const useDotNotation = this.getNodeParameter('options.useDotNotation', 0, false) as boolean;
const dateFields = prepareFields(
this.getNodeParameter('options.dateFields', 0, '') as string,
);
const oidFields = prepareFields(
this.getNodeParameter('options.oidFields', 0, '') as string,
);
const updateKey = ((this.getNodeParameter('updateKey', 0) as string) || '').trim();
const updateOptions = (this.getNodeParameter('upsert', 0) as boolean)
? { upsert: true }
: undefined;
const updateItems = prepareItems(items, fields, updateKey, useDotNotation, dateFields, oidFields);
for (const item of updateItems) {
try {
const filter = { [updateKey]: item[updateKey] };
if (updateKey === '_id') {
filter[updateKey] = new ObjectId(item[updateKey] as string);
delete item._id;
}
await mdb
.collection(this.getNodeParameter('collection', 0) as string)
.findOneAndReplace(filter, item, updateOptions as FindOneAndReplaceOptions);
} catch (error) {
if (this.continueOnFail()) {
item.json = { error: (error as JsonObject).message };
continue;
}
throw error;
}
}
responseData = updateItems;
} else if (operation === 'findOneAndUpdate') {
// ----------------------------------
// findOneAndUpdate
// ----------------------------------
const fields = prepareFields(this.getNodeParameter('fields', 0) as string);
const useDotNotation = this.getNodeParameter('options.useDotNotation', 0, false) as boolean;
const dateFields = prepareFields(
this.getNodeParameter('options.dateFields', 0, '') as string,
);
const oidFields = prepareFields(
this.getNodeParameter('options.oidFields', 0, '') as string,
);
const updateKey = ((this.getNodeParameter('updateKey', 0) as string) || '').trim();
const updateOptions = (this.getNodeParameter('upsert', 0) as boolean)
? { upsert: true }
: undefined;
const updateItems = prepareItems(items, fields, updateKey, useDotNotation, dateFields, oidFields);
for (const item of updateItems) {
try {
const filter = { [updateKey]: item[updateKey] };
if (updateKey === '_id') {
filter[updateKey] = new ObjectId(item[updateKey] as string);
delete item._id;
}
await mdb
.collection(this.getNodeParameter('collection', 0) as string)
.findOneAndUpdate(filter, { $set: item }, updateOptions as FindOneAndUpdateOptions);
} catch (error) {
if (this.continueOnFail()) {
item.json = { error: (error as JsonObject).message };
continue;
}
throw error;
}
}
responseData = updateItems;
} else if (operation === 'insert') {
// ----------------------------------
// insert
// ----------------------------------
try {
// Prepare the data to insert and copy it to be returned
const fields = prepareFields(this.getNodeParameter('fields', 0) as string);
const useDotNotation = this.getNodeParameter('options.useDotNotation', 0, false) as boolean;
const dateFields = prepareFields(
this.getNodeParameter('options.dateFields', 0, '') as string,
);
const oidFields = prepareFields(
this.getNodeParameter('options.oidFields', 0, '') as string,
);
const insertItems = prepareItems(items, fields, '', useDotNotation, dateFields, oidFields);
const { insertedIds } = await mdb
.collection(this.getNodeParameter('collection', 0) as string)
.insertMany(insertItems);
// Add the id to the data
for (const i of Object.keys(insertedIds)) {
responseData.push({
...insertItems[parseInt(i, 10)],
id: insertedIds[parseInt(i, 10)] as unknown as string,
});
}
} catch (error) {
if (this.continueOnFail()) {
responseData = [{ error: (error as JsonObject).message }];
} else {
throw error;
}
}
} else if (operation === 'update') {
// ----------------------------------
// update
// ----------------------------------
const fields = prepareFields(this.getNodeParameter('fields', 0) as string);
const useDotNotation = this.getNodeParameter('options.useDotNotation', 0, false) as boolean;
const dateFields = prepareFields(
this.getNodeParameter('options.dateFields', 0, '') as string,
);
const oidFields = prepareFields(
this.getNodeParameter('options.oidFields', 0, '') as string,
);
const updateKey = ((this.getNodeParameter('updateKey', 0) as string) || '').trim();
const updateOptions = (this.getNodeParameter('upsert', 0) as boolean)
? { upsert: true }
: undefined;
const updateItems = prepareItems(items, fields, updateKey, useDotNotation, dateFields, oidFields);
for (const item of updateItems) {
try {
const filter = { [updateKey]: item[updateKey] };
if (updateKey === '_id') {
filter[updateKey] = new ObjectId(item[updateKey] as string);
delete item._id;
}
await mdb
.collection(this.getNodeParameter('collection', 0) as string)
.updateOne(filter, { $set: item }, updateOptions as UpdateOptions);
} catch (error) {
if (this.continueOnFail()) {
item.json = { error: (error as JsonObject).message };
continue;
}
throw error;
}
}
responseData = updateItems;
} else {
if (this.continueOnFail()) {
responseData = [{ error: `The operation "${operation}" is not supported!` }];
} else {
throw new NodeOperationError(
this.getNode(),
`The operation "${operation}" is not supported!`,
{ itemIndex: 0 },
);
}
}
await client.close();
const executionData = this.helpers.constructExecutionMetaData(
this.helpers.returnJsonArray(responseData),
{ itemData: { item: 0 } },
);
returnItems.push(...executionData);
return this.prepareOutputData(returnItems);
}
}