generated from moevm/nsql-clean-tempate
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: connect the project to the database
- Loading branch information
1 parent
7123f31
commit 6e66f79
Showing
2 changed files
with
65 additions
and
0 deletions.
There are no files selected for viewing
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
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" | ||
} | ||
} |
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
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); |