1 | import { MongoClient, ObjectId } 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 | * Find document by id |
17 | * Fetch a single document by its `_id` (ObjectId hex string, or a raw string id). |
18 | */ |
19 | export async function main( |
20 | auth: Mongodb, |
21 | collection: string, |
22 | document_id: string, |
23 | projection?: Record<string, number>, |
24 | database?: string, |
25 | ) { |
26 | const _id = ObjectId.isValid(document_id) |
27 | ? new ObjectId(document_id) |
28 | : document_id; |
29 | const client = await mongoClient(auth); |
30 | try { |
31 | return await client |
32 | .db(database || auth.db) |
33 | .collection(collection) |
34 | .findOne({ _id }, projection ? { projection } : undefined); |
35 | } finally { |
36 | await client.close(); |
37 | } |
38 | } |
39 |
|
40 | async function mongoClient(auth: Mongodb) { |
41 | const hosts = auth.servers.map((s) => `${s.host}:${s.port}`).join(","); |
42 | const options: any = { tls: auth.tls }; |
43 | if (auth.credential?.username) { |
44 | options.auth = { |
45 | username: auth.credential.username, |
46 | password: auth.credential.password, |
47 | }; |
48 | options.authSource = auth.credential.db; |
49 | if (auth.credential.mechanism) { |
50 | options.authMechanism = auth.credential.mechanism; |
51 | } |
52 | } |
53 | const client = new MongoClient(`mongodb://${hosts}`, options); |
54 | await client.connect(); |
55 | return client; |
56 | } |
57 |
|