import { MongoClient } from "mongodb@6";
type Mongodb = {
servers: { host: string; port: number }[];
credential: {
username: string;
password: string;
db: string;
mechanism?: string;
};
db: string;
tls: boolean;
};
/**
* Create many new documents
* Insert multiple documents into a collection.
*/
export async function main(
auth: Mongodb,
collection: string,
documents: Record<string, any>[],
database?: string,
) {
const client = await mongoClient(auth);
try {
return await client
.db(database || auth.db)
.collection(collection)
.insertMany(documents);
} finally {
await client.close();
}
}
async function mongoClient(auth: Mongodb) {
const hosts = auth.servers.map((s) => `${s.host}:${s.port}`).join(",");
const options: any = { tls: auth.tls };
if (auth.credential?.username) {
options.auth = {
username: auth.credential.username,
password: auth.credential.password,
};
options.authSource = auth.credential.db;
if (auth.credential.mechanism) {
options.authMechanism = auth.credential.mechanism;
}
}
const client = new MongoClient(`mongodb://${hosts}`, options);
await client.connect();
return client;
}
Submitted by hugo989 4 days ago