-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
31 lines (24 loc) · 866 Bytes
/
Copy pathapp.js
File metadata and controls
31 lines (24 loc) · 866 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
const http = require("http");
const { MongoClient } = require("mongodb");
const url = process.env.MONGODB_URI || "mongodb://mongo:27017";
const client = new MongoClient(url);
async function start() {
try {
await client.connect();
console.log("Connected to MongoDB");
const db = client.db("mydb");
const collection = db.collection("test");
const server = http.createServer(async (req, res) => {
await collection.insertOne({ message: "Hello MongoDB", time: new Date() });
const count = await collection.countDocuments();
res.writeHead(200, { "Content-Type": "text/plain" });
res.end(`Hello from Node + MongoDB. Total docs: ${count}`);
});
server.listen(3000, () => {
console.log("App running on port 3000");
});
} catch (err) {
console.error("MongoDB connection error:", err);
}
}
start();