54 lines
1.5 KiB
JavaScript
54 lines
1.5 KiB
JavaScript
// Import necessary modules
|
|
import { MongoClient } from 'mongodb';
|
|
|
|
import dotenv from 'dotenv';
|
|
dotenv.config()
|
|
|
|
// MongoDB connection URI
|
|
const uri = process.env.MONGO_URL;
|
|
|
|
// Function to connect to the database
|
|
export const connectToDatabase = async () => {
|
|
try {
|
|
const client = await MongoClient.connect(uri);
|
|
return client;
|
|
} catch (error) {
|
|
console.error('Error connecting to the database:', error);
|
|
throw error;
|
|
}
|
|
};
|
|
|
|
// Function to insert a document into the collection
|
|
export const insertDocument = async (collectionName, document) => {
|
|
const db = await connectToDatabase();
|
|
try {
|
|
const collection = db.db().collection(collectionName);
|
|
const result = await collection.insertOne(document);
|
|
console.log('Document inserted:', result.insertedId);
|
|
return result.insertedId;
|
|
} catch (error) {
|
|
console.error('Error inserting document:', error);
|
|
throw error;
|
|
} finally {
|
|
// Close the connection
|
|
await db.close();
|
|
}
|
|
};
|
|
|
|
// Function to retrieve documents from the collection
|
|
export const getDocuments = async (collectionName) => {
|
|
const db = await connectToDatabase();
|
|
try {
|
|
const collection = db.db().collection(collectionName);
|
|
const documents = await collection.find({}).toArray();
|
|
console.log('Documents retrieved:', documents);
|
|
return documents;
|
|
} catch (error) {
|
|
console.error('Error retrieving documents:', error);
|
|
throw error;
|
|
} finally {
|
|
// Close the connection
|
|
await db.close();
|
|
}
|
|
};
|