Skip to content

Instantly share code, notes, and snippets.

@sanya29

sanya29/index.js Secret

Last active February 5, 2021 08:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sanya29/1c22caa7a538d64c54c66834158a18a0 to your computer and use it in GitHub Desktop.
Save sanya29/1c22caa7a538d64c54c66834158a18a0 to your computer and use it in GitHub Desktop.
Boilerplate code for connecting to MongoDB Atlas in your Node.js application
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