/** * MongoDB Connection Helper * Generated by vai v{{vaiVersion}} on {{generatedAt}} * * Database: {{db}} * Collection: {{collection}} */ const { MongoClient } = require('mongodb'); const MONGODB_URI = process.env.MONGODB_URI; if (!MONGODB_URI) { throw new Error('MONGODB_URI environment variable is required'); } let client = null; let db = null; /** * Connect to MongoDB and return the database instance. * Reuses existing connection if available. * @returns {Promise} */ async function connect() { if (db) return db; client = new MongoClient(MONGODB_URI); await client.connect(); db = client.db('{{db}}'); console.log('Connected to MongoDB: {{db}}'); return db; } /** * Get the documents collection. * @returns {Promise} */ async function getCollection() { const database = await connect(); return database.collection('{{collection}}'); } /** * Close the MongoDB connection. */ async function close() { if (client) { await client.close(); client = null; db = null; } } /** * Perform a vector search on the collection. * @param {number[]} embedding - Query embedding vector * @param {object} options - Search options * @param {number} options.limit - Number of results (default: 10) * @param {number} options.numCandidates - Candidates to consider (default: limit * 10) * @param {object} options.filter - Optional pre-filter * @returns {Promise>} */ async function vectorSearch(embedding, options = {}) { const collection = await getCollection(); const limit = options.limit || 10; const numCandidates = options.numCandidates || limit * 10; const pipeline = [ { $vectorSearch: { index: '{{index}}', path: '{{field}}', queryVector: embedding, numCandidates, limit, {{#if filter}} filter: options.filter, {{/if}} }, }, { $project: { _id: 1, text: 1, metadata: 1, score: { $meta: 'vectorSearchScore' }, }, }, ]; const results = await collection.aggregate(pipeline).toArray(); return results.map(doc => ({ document: doc, score: doc.score, })); } /** * Insert documents with embeddings. * @param {Array<{text: string, embedding: number[], metadata?: object}>} docs * @returns {Promise<{insertedCount: number}>} */ async function insertDocuments(docs) { const collection = await getCollection(); const documents = docs.map(doc => ({ text: doc.text, {{field}}: doc.embedding, metadata: doc.metadata || {}, _embeddedAt: new Date(), _model: '{{model}}', })); const result = await collection.insertMany(documents); return { insertedCount: result.insertedCount }; } module.exports = { connect, getCollection, close, vectorSearch, insertDocuments, };