1
Create Many New Documents
One script reply has been approved by the moderators Verified
Created by adam186 484 days ago Viewed 4299 times
0
Submitted by adam186 Deno
Verified 484 days ago
1
import { MongoClient } from "https://deno.land/x/atlas_sdk@v1.0.3/mod.ts";
2

3
/**
4
 * @param data_source For example: `Cluster0`
5
 */
6
type MongodbRest = {
7
  endpoint: string;
8
  api_key: string;
9
};
10
export async function main(
11
  auth: MongodbRest,
12
  data_source: string,
13
  database: string,
14
  collection: string,
15
  documents: Record<string, any>[],
16
) {
17
  const client = new MongoClient({
18
    endpoint: auth.endpoint,
19
    dataSource: data_source,
20
    auth: { apiKey: auth.api_key },
21
  });
22
  const docs = client.database(database).collection(collection);
23

24
  let items: Record<string, any>[];
25
  try {
26
    items = documents.map((doc) =>
27
      typeof doc === "string" ? JSON.parse(doc) : doc,
28
    );
29
  } catch (err) {
30
    throw Error(`\nReceived array of strings in the 'documents' argument.
31
Attempted to parse them into objects but the process failed with the following error:\n${err}`);
32
  }
33

34
  return await docs.insertMany(items);
35
}
36