Find Document by Id
One script reply has been approved by the moderators Verified
Created by maximelambercier 1351 days ago Picked 10 times
Submitted by adam186 Deno
Verified 285 days ago
1
import { removeObjectEmptyFields } from "https://deno.land/x/[email protected]/mod.ts";
2
import {
3
  MongoClient,
4
  ObjectId,
5
} from "https://deno.land/x/[email protected]/mod.ts";
6

7
/**
8
 * @param data_source For example: `Cluster0`
9
 */
10
type MongodbRest = {
11
  endpoint: string;
12
  api_key: string;
13
};
14
export async function main(
15
  auth: MongodbRest,
16
  data_source: string,
17
  database: string,
18
  collection: string,
19
  document_id: string,
20
  projection?: Record<string, number>,
21
) {
22
  const client = new MongoClient({
23
    endpoint: auth.endpoint,
24
    dataSource: data_source,
25
    auth: { apiKey: auth.api_key },
26
  });
27
  const db = client.database(database);
28
  return await db
29
    .collection(collection)
30
    .findOne(
31
      { _id: new ObjectId(document_id) },
32
      removeObjectEmptyFields({ projection }),
33
    );
34
}
35

Other submissions