Last active
February 7, 2025 07:03
-
-
Save l10rdev/61c3446ad5a78be0994fa19f72044e46 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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