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 | * Search documents |
17 | * Find documents in a collection matching a filter (with optional projection, sort, limit and skip). |
18 | */ |
19 | export async function main( |
20 | auth: Mongodb, |
21 | collection: string, |
22 | filter?: Record<string, any>, |
23 | projection?: Record<string, number>, |
24 | sort?: Record<string, number>, |
25 | limit?: number, |
26 | skip?: number, |
27 | database?: string, |
28 | ) { |
29 | const client = await mongoClient(auth); |
30 | try { |
31 | let cursor = client |
32 | .db(database || auth.db) |
33 | .collection(collection) |
34 | .find(filter ?? {}); |
35 | if (projection) cursor = cursor.project(projection); |
36 | if (sort) cursor = cursor.sort(sort); |
37 | if (skip) cursor = cursor.skip(skip); |
38 | if (limit) cursor = cursor.limit(limit); |
39 | return await cursor.toArray(); |
40 | } finally { |
41 | await client.close(); |
42 | } |
43 | } |
44 |
|
45 | async function mongoClient(auth: Mongodb) { |
46 | const hosts = auth.servers.map((s) => `${s.host}:${s.port}`).join(","); |
47 | const options: any = { tls: auth.tls }; |
48 | if (auth.credential?.username) { |
49 | options.auth = { |
50 | username: auth.credential.username, |
51 | password: auth.credential.password, |
52 | }; |
53 | options.authSource = auth.credential.db; |
54 | if (auth.credential.mechanism) { |
55 | options.authMechanism = auth.credential.mechanism; |
56 | } |
57 | } |
58 | const client = new MongoClient(`mongodb://${hosts}`, options); |
59 | await client.connect(); |
60 | return client; |
61 | } |
62 |
|