Skip to content

Commit

Permalink
feat: add aggregate db operation (#91)
Browse files Browse the repository at this point in the history
  • Loading branch information
leNicDev authored Jun 29, 2024
1 parent d438ed3 commit a0a0d5b
Showing 1 changed file with 28 additions and 2 deletions.
30 changes: 28 additions & 2 deletions src/main/server/database/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as alt from 'alt-server';
import { MongoClient, Db, InsertOneResult, ObjectId } from 'mongodb';
import { MongoClient, Db, InsertOneResult, ObjectId, AggregateOptions } from 'mongodb';
import * as Utility from '@Shared/utility/index.js';
import { CollectionNames } from '../document/shared.js';

Expand Down Expand Up @@ -84,7 +84,7 @@ export function useDatabase() {

try {
await client.createCollection(name);
} catch (err) {}
} catch (err) { }
}

/**
Expand Down Expand Up @@ -253,6 +253,31 @@ export function useDatabase() {
}
}

/**
* Runs an aggregation query
*
* If the collection does not exist it will return `undefined`
*
* @export
* @param {string} collection
* @param {any[]} pipeline
* @param {AggregateOptions} options
* @return {Promise<T[] | undefined>}
*/
async function aggregate<T extends { _id: string }>(collection: string, pipeline: any[], options?: AggregateOptions): Promise<T[] | undefined> {
const client = await getClient();

try {
const cursor = await client.collection(collection).aggregate(pipeline, options);
const documents = await cursor.toArray();
return documents.map((x) => {
return { ...x, _id: String(x._id) };
}) as (T & { _id: string })[];
} catch (err) {
return undefined;
}
}

return {
create,
createCollection,
Expand All @@ -267,5 +292,6 @@ export function useDatabase() {
return isConnected;
},
update,
aggregate,
};
}

0 comments on commit a0a0d5b

Please sign in to comment.