Skip to content

Commit

Permalink
feat: connect the project to the database
Browse files Browse the repository at this point in the history
  • Loading branch information
SyrtcevaDaria committed Sep 22, 2024
1 parent 7123f31 commit 6e66f79
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
23 changes: 23 additions & 0 deletions hello_world/package.json
Original file line number Diff line number Diff line change
@@ -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"
}
}
42 changes: 42 additions & 0 deletions hello_world/server.js
Original file line number Diff line number Diff line change
@@ -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);

0 comments on commit 6e66f79

Please sign in to comment.