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 | * Update a document |
17 | * Update the first document matching the filter. `update` uses update operators, |
18 | * e.g. `{ "$set": { "field": "value" } }`. |
19 | */ |
20 | export async function main( |
21 | auth: Mongodb, |
22 | collection: string, |
23 | filter: Record<string, any>, |
24 | update: Record<string, any>, |
25 | upsert?: boolean, |
26 | database?: string, |
27 | ) { |
28 | const client = await mongoClient(auth); |
29 | try { |
30 | return await client |
31 | .db(database || auth.db) |
32 | .collection(collection) |
33 | .updateOne(filter, update, { upsert: upsert ?? false }); |
34 | } finally { |
35 | await client.close(); |
36 | } |
37 | } |
38 |
|
39 | async function mongoClient(auth: Mongodb) { |
40 | const hosts = auth.servers.map((s) => `${s.host}:${s.port}`).join(","); |
41 | const options: any = { tls: auth.tls }; |
42 | if (auth.credential?.username) { |
43 | options.auth = { |
44 | username: auth.credential.username, |
45 | password: auth.credential.password, |
46 | }; |
47 | options.authSource = auth.credential.db; |
48 | if (auth.credential.mechanism) { |
49 | options.authMechanism = auth.credential.mechanism; |
50 | } |
51 | } |
52 | const client = new MongoClient(`mongodb://${hosts}`, options); |
53 | await client.connect(); |
54 | return client; |
55 | } |
56 |
|