From 6e66f79e4f0d08d960d27841f6fbd0d544a1543f Mon Sep 17 00:00:00 2001 From: SyrtcevaDaria Date: Sun, 22 Sep 2024 11:56:35 +0300 Subject: [PATCH] feat: connect the project to the database --- hello_world/package.json | 23 ++++++++++++++++++++++ hello_world/server.js | 42 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 hello_world/package.json create mode 100644 hello_world/server.js diff --git a/hello_world/package.json b/hello_world/package.json new file mode 100644 index 0000000..1a8a978 --- /dev/null +++ b/hello_world/package.json @@ -0,0 +1,23 @@ +{ + "name": "backend", + "version": "1.0.0", + "main": "index.js", + "scripts": { + "dev": "nodemon server.js", + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [], + "author": "", + "license": "ISC", + "description": "", + "dependencies": { + "body-parser": "^1.20.3", + "cors": "^2.8.5", + "express": "^4.21.0", + "mongodb": "^6.9.0", + "mongoose": "^8.6.2" + }, + "devDependencies": { + "nodemon": "^3.1.4" + } +} diff --git a/hello_world/server.js b/hello_world/server.js new file mode 100644 index 0000000..f456802 --- /dev/null +++ b/hello_world/server.js @@ -0,0 +1,42 @@ +const { MongoClient } = require('mongodb'); + +const url = 'mongodb://localhost:27017/mongo'; + +const client = new MongoClient(url); + +async function addCurrentDate(db) { + try { + const currentDate = new Date(); + const collection = db.collection('dates'); + const result = await collection.insertOne({ date: currentDate }); + console.log('Date inserted:', result.insertedId); + } catch (error) { + console.error('Error inserting date:', error); + } +} + +async function getAllDates(db) { + try { + const collection = db.collection('dates'); + return await collection.find().toArray(); + } catch (error) { + console.error('Error fetching dates:', error); + throw error; + } +} + +async function main() { + try { + await client.connect(); + const db = await client.db() + await addCurrentDate(db); + const dates = await getAllDates(db); + console.log('Dates found:', dates); + } catch (error) { + console.error('Error:', error); + } finally { + await client.close(); + } +} + +main().catch(console.error);