demeter

Autonomous Hydroponic Intelligence

backend/node_server/config/db.js (2157B)


 1const path = require("path");
 2require("dotenv").config({
 3  path: path.join(__dirname, "..", "..", "..", ".env"),
 4});
 5const { QdrantClient } = require("@qdrant/js-client-rest");
 6const { mongoose } = require("mongoose");
 7
 8const COLLECTION_NAME = "Farm_Memory";
 9
10// 1. Initialize Client with the Fix
11console.log("🔧 Initializing Qdrant Client...", process.env.QDRANT_URL);
12const client = new QdrantClient({
13  url: process.env.QDRANT_URL,
14  apiKey: process.env.QDRANT_API_KEY,
15  checkCompatibility: false, // 👈 FIX: Skips the failing version check
16});
17
18// 2. Indexing & Collection Setup Function
19const initDB = async () => {
20  try {
21    // Test connection first
22    // If this fails, check your QDRANT_URL in .env
23    const result = await client.getCollections();
24
25    const exists = result.collections.some((c) => c.name === COLLECTION_NAME);
26
27    // A. Create Collection if missing
28    if (!exists) {
29      await client.createCollection(COLLECTION_NAME, {
30        vectors: { size: 4, distance: "Cosine" },
31      });
32      console.log(`✅ Collection '${COLLECTION_NAME}' created.`);
33    }
34
35    // B. Create Index
36    // Using try-catch here specifically for index creation to prevent crashing if it already exists
37    try {
38      await client.createPayloadIndex(COLLECTION_NAME, {
39        field_name: "crop_id",
40        field_schema: "keyword",
41      });
42      console.log("✅ Indexes verified.");
43    } catch (indexError) {
44      // Ignore error if index already exists
45      if (!indexError.message.includes("already exists")) {
46        console.warn("⚠️ Note on Index:", indexError.message);
47      }
48    }
49  } catch (err) {
50    console.error("❌ DB Connection Failed:");
51    console.error("   Reason:", err.message);
52    console.error(
53      "   Check your QDRANT_URL in .env. It must start with 'http://' or 'https://'",
54    );
55  }
56};
57
58const connectMongoDB = async () => {
59  try {
60    await mongoose.connect(process.env.MONGODB_URI, {});
61    console.log("✅ Connected to MongoDB");
62  } catch (err) {
63    console.error("❌ MongoDB Connection Failed:", err.message);
64  }
65};
66
67module.exports = { client, initDB, connectMongoDB, COLLECTION_NAME };