1 | import { MongoClient } from "mongodb@6"; |
2 |
|
3 | type Mongodb = { |
4 | servers: { host: string; port: number }[]; |
5 | credential: { |
6 | username: string; |
7 | password: string; |
8 | db: string; |
9 | mechanism?: string; |
10 | }; |
11 | db: string; |
12 | tls: boolean; |
13 | }; |
14 |
|
15 | |
16 | * Create many new documents |
17 | * Insert multiple documents into a collection. |
18 | */ |
19 | export async function main( |
20 | auth: Mongodb, |
21 | collection: string, |
22 | documents: Record<string, any>[], |
23 | database?: string, |
24 | ) { |
25 | const client = await mongoClient(auth); |
26 | try { |
27 | return await client |
28 | .db(database || auth.db) |
29 | .collection(collection) |
30 | .insertMany(documents); |
31 | } finally { |
32 | await client.close(); |
33 | } |
34 | } |
35 |
|
36 | async function mongoClient(auth: Mongodb) { |
37 | const hosts = auth.servers.map((s) => `${s.host}:${s.port}`).join(","); |
38 | const options: any = { tls: auth.tls }; |
39 | if (auth.credential?.username) { |
40 | options.auth = { |
41 | username: auth.credential.username, |
42 | password: auth.credential.password, |
43 | }; |
44 | options.authSource = auth.credential.db; |
45 | if (auth.credential.mechanism) { |
46 | options.authMechanism = auth.credential.mechanism; |
47 | } |
48 | } |
49 | const client = new MongoClient(`mongodb://${hosts}`, options); |
50 | await client.connect(); |
51 | return client; |
52 | } |
53 |
|