1 | import { MongoClient } from "https://deno.land/x/[email protected]/mod.ts"; |
2 |
|
3 | |
4 | * @param data_source For example: `Cluster0` |
5 | */ |
6 | type MongodbRest = { |
7 | endpoint: string; |
8 | api_key: string; |
9 | }; |
10 | export async function main( |
11 | auth: MongodbRest, |
12 | data_source: string, |
13 | database: string, |
14 | collection: string, |
15 | documents: Record<string, any>[], |
16 | ) { |
17 | const client = new MongoClient({ |
18 | endpoint: auth.endpoint, |
19 | dataSource: data_source, |
20 | auth: { apiKey: auth.api_key }, |
21 | }); |
22 | const docs = client.database(database).collection(collection); |
23 |
|
24 | let items: Record<string, any>[]; |
25 | try { |
26 | items = documents.map((doc) => |
27 | typeof doc === "string" ? JSON.parse(doc) : doc, |
28 | ); |
29 | } catch (err) { |
30 | throw Error(`\nReceived array of strings in the 'documents' argument. |
31 | Attempted to parse them into objects but the process failed with the following error:\n${err}`); |
32 | } |
33 |
|
34 | return await docs.insertMany(items); |
35 | } |
36 |
|