Skip to content

Instantly share code, notes, and snippets.

@l10rdev
Last active February 7, 2025 07:03
Show Gist options
  • Save l10rdev/61c3446ad5a78be0994fa19f72044e46 to your computer and use it in GitHub Desktop.
Save l10rdev/61c3446ad5a78be0994fa19f72044e46 to your computer and use it in GitHub Desktop.
const mongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const express = require('express');
const objectId = require('mongodb').ObjectId;
const server = express();
const MongoClient = require('mongodb').MongoClient;
server.use(bodyParser.json());
const connectionString = "";
server.get('/technologies', async (req, res) => {
let client;
try {
client = await MongoClient.connect(connectionString);
const db = client.db('techradar');
const collection = db.collection('technologies');
const result = await collection.find({}).toArray();
res.send(result);
} catch (error) {
console.log(error)
console.log(error)
res.status(500).send({ error: 'Error fetching technologies' });
} finally {
// await client.close(); // Ensure the connection is closed
}
});
server.get('/technologies/:id', async (req, res) => {
let client;
try {
client = await MongoClient.connect(connectionString);
const db = client.db('techradar');
const collection = db.collection('technologies');
const result = await collection.findOne({ _id: objectId(req.params.id) });
if (result) {
res.send(result);
} else {
res.status(404);
}
res.end();
} catch (error) {
res.status(500).send({ error: 'Error fetching technologies' });
} finally {
await client.close(); // Ensure the connection is closed
}
});
server.post('/technologies', async (req, res) => {
let client;
try {
client = await MongoClient.connect(connectionString);
const db = client.db('techradar');
const collection = db.collection('technologies');
await collection.insertOne(req.body);
res.status(201);
res.end();
} catch (error) {
res.status(500).send({ error: 'Error fetching technologies' });
} finally {
await client.close(); // Ensure the connection is closed
}
});
module.exports = server;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment