1

Find Document by Id

by
Published Jun 6, 2022
Script mongodb Verified

The script

Submitted by hugo989 Bun
Verified 6 days ago
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

Other submissions
  • Submitted by rossmccrann Deno
    Created 1422 days ago
    1
    import * as wmill from "https://deno.land/x/[email protected]/mod.ts";
    2
    import { Bson, MongoClient } from "https://deno.land/x/[email protected]/mod.ts";
    3
    
    
    4
    /*
    5
    @param: {wmill.Resource} mongodb - Resource containing mongodb connection object
    6
    example:
    7
    await client.connect({
    8
      db: "<db_name>",
    9
      tls: true,
    10
      servers: [
    11
        {
    12
          host: "<db_cluster_url>",
    13
          port: 27017,
    14
        },
    15
      ],
    16
      credential: {
    17
        username: "<username>",
    18
        password: "<password>",
    19
        db: "<db_name>",
    20
        mechanism: "SCRAM-SHA-1",
    21
      },
    22
    });
    23
    */
    24
    
    
    25
    export async function main(
    26
        mongodb_con: wmill.Resource<"mongodb">,
    27
        db_name: string,
    28
        collection_name: string,
    29
        objectId: string
    30
    ) {
    31
        const client = new MongoClient();
    32
    
    
    33
        // Connecting to a Mongo Atlas Database
    34
        const resp = await client.connect(mongodb_con);
    35
    
    
    36
        const db = client.database(db_name);
    37
        const collect = db.collection(collection_name);
    38
    
    
    39
        const collect_single = await collect.findOne({ _id: objectId });
    40
    
    
    41
        return (collect_single ? 'Document Found in MongoDB' : 'Document Not Found');
    42
    }
    43
    
    
  • Submitted by adam186 Deno
    Created 398 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