-
-
Save sanya29/1c22caa7a538d64c54c66834158a18a0 to your computer and use it in GitHub Desktop.
Boilerplate code for connecting to MongoDB Atlas in your Node.js application
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 express = require('express'); | |
const cors = require('cors'); | |
const MongoClient = require('mongodb').MongoClient; | |
const app = express(); | |
app.use(express.json()); | |
app.use(cors()); | |
app.use(express.urlencoded({ extended: true })); | |
let db | |
app.get('/health', (req, res) => { | |
return res.status(200).send({ message: "GET /health successful" }) | |
}) | |
app.get('/addUser', async (req, res) => { | |
// name, age | |
const { name, age } = req.query | |
await db.collection("users").insertOne({ | |
name, | |
age, | |
complex: { | |
can: "be literally anything", | |
date: Date() | |
} | |
}) | |
return res.status(201).send({ | |
message: "User created successfully." | |
}) | |
}) | |
app.get('/addTeacher', async (req, res) => { | |
// name, age | |
const { name, age } = req.query | |
await db.collection("users").insertOne({ | |
name, | |
age, | |
complex: { | |
can: "be literally anything", | |
date: Date(), | |
test: [ | |
"hello", | |
"there" | |
] | |
} | |
}) | |
return res.status(201).send({ | |
message: "User created successfully." | |
}) | |
}) | |
const connectToDB = async () => { | |
const uri = "mongodb+srv://superuser:superpassword@cluster0.w2do3.mongodb.net/test?retryWrites=true&w=majority"; | |
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); | |
client.connect(err => { | |
if (err) { | |
console.log(err) | |
} | |
db = client.db("test"); | |
console.log("Connected to the database") | |
// client.close(); | |
}); | |
} | |
app.listen(9000, () => { | |
console.log(`Listening on Port 9000`) | |
}) | |
connectToDB() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment