import { MongoClient, ObjectId } from "mongodb@6";
type Mongodb = {
servers: { host: string; port: number }[];
credential: {
username: string;
password: string;
db: string;
mechanism?: string;
};
db: string;
tls: boolean;
};
/**
* Find document by id
* Fetch a single document by its `_id` (ObjectId hex string, or a raw string id).
*/
export async function main(
auth: Mongodb,
collection: string,
document_id: string,
projection?: Record<string, number>,
database?: string,
) {
const _id = ObjectId.isValid(document_id)
? new ObjectId(document_id)
: document_id;
const client = await mongoClient(auth);
try {
return await client
.db(database || auth.db)
.collection(collection)
.findOne({ _id }, projection ? { projection } : undefined);
} 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 6 days ago