mongo-ffb-production.repository.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { Db, ObjectId, WithId } from 'mongodb';
  2. import { FFBProduction } from 'src/FFB/ffb-production.schema';
  3. export class FFBProductionRepository {
  4. private readonly collectionName = 'FFB Production';
  5. constructor(private readonly db: Db) { }
  6. private get collection() {
  7. return this.db.collection<FFBProduction & { vector?: number[] }>(this.collectionName);
  8. }
  9. async init() {
  10. const collections = await this.db.listCollections({ name: this.collectionName }).toArray();
  11. if (collections.length === 0) {
  12. await this.db.createCollection(this.collectionName);
  13. console.log(`✅ Created collection: ${this.collectionName}`);
  14. }
  15. }
  16. async create(ffb: FFBProduction & { vector?: number[] }): Promise<FFBProduction & { vector?: number[] }> {
  17. const result = await this.collection.insertOne({
  18. ...ffb,
  19. productionDate: new Date(ffb.productionDate),
  20. vector: ffb.vector, // optional vector
  21. });
  22. return { ...ffb, _id: result.insertedId.toString() };
  23. }
  24. async findAll(filter: Record<string, any> = {}): Promise<(FFBProduction & { vector?: number[] })[]> {
  25. const results = await this.collection.find(filter).toArray();
  26. return results.map((r: WithId<FFBProduction & { vector?: number[] }>) => ({
  27. ...r,
  28. _id: r._id?.toString(),
  29. }));
  30. }
  31. async findById(id: string): Promise<(FFBProduction & { vector?: number[] }) | null> {
  32. const result = await this.collection.findOne({ _id: new ObjectId(id) as any });
  33. return result ? { ...result, _id: result._id.toString() } : null;
  34. }
  35. async delete(id: string) {
  36. return this.collection.deleteOne({ _id: new ObjectId(id) as any });
  37. }
  38. /** Optional: helper for vector search via aggregation */
  39. async vectorSearch(vector: number[], k = 5, numCandidates = 50) {
  40. return this.collection
  41. .aggregate([
  42. {
  43. $vectorSearch: {
  44. index: 'vector_index',
  45. queryVector: vector,
  46. path: 'vector',
  47. numCandidates,
  48. limit: k
  49. }
  50. },
  51. {
  52. $project: {
  53. _id: 1,
  54. productionDate: 1,
  55. site: 1,
  56. phase: 1,
  57. block: 1,
  58. quantity: 1,
  59. quantityUom: 1,
  60. weight: 1,
  61. weightUom: 1,
  62. score: { "$meta": "vectorSearchScore" } // correctly get the score
  63. }
  64. }
  65. ])
  66. .toArray();
  67. }
  68. }