I am new to web development in general. I am trying to insert and find documents in a local mongoDB database through GET and POST requests. I am doing this with a Node.js/Express web server. I've managed to get something working, but I'm not sure if I'm doing the right thing.
First, I wrote client.html to send POST requests.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Client</title>
</head>
<body>
<p>Insert something into the database:</p>
<form action="/items" method="POST">
<input type="text" name="item">
<button type="submit">Submit</button>
</form>
</body>
</html>
After reading the mongoDB documentation for Node.js, I decided to write my Node.js server as follows, putting all my routes under one connection (approach 1):
const express = require("express");
const app = express();
const port = 5000;
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url, { useUnifiedTopology: true });
app.use(express.urlencoded({ extended: true }));
client.connect(function(err) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db("my_db");
const itemsCollection = db.collection("items");
app.get("/", function(req, res) {
res.sendFile(__dirname + "/client.html");
});
// GET request - find documents
app.get("/items", function(req, res) {
itemsCollection.find().toArray(function(err, docs) {
assert.equal(null, err);
console.log(docs);
});
});
// POST request - insert document
app.post("/items", function(req, res) {
itemsCollection.insertOne(req.body, function(err, result) {
assert.equal(null, err);
res.redirect("/");
});
});
app.listen(port, function() {
console.log(`Listening on port: ${port}`);
});
});
However, I've also seen people create a new connection for every route, which would be something like this (approach 2):
const express = require("express");
const app = express();
const port = 5000;
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url, { useUnifiedTopology: true });
app.use(express.urlencoded({ extended: true }));
app.get("/", function(req, res) {
res.sendFile(__dirname + "/client.html");
});
// GET request - find documents
app.get("/items", function(req, res) {
client.connect(function(err) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db("my_db");
const itemsCollection = db.collection("items");
itemsCollection.find().toArray(function(err, docs) {
assert.equal(null, err);
console.log(docs);
});
});
});
// POST request - insert document
app.post("/items", function(req, res) {
client.connect(function(err) {
assert.equal(null, err);
const db = client.db("my_db");
const itemsCollection = db.collection("items");
itemsCollection.insertOne(req.body, function(err, result) {
assert.equal(null, err);
res.redirect("/");
});
});
});
app.listen(port, function() {
console.log(`Listening on port: ${port}`);
});
Both approaches successfully complete the database operations. I would like to know:
- Which of these approaches (if any) are recommended, and why?
- Should I be calling client.close() anywhere in my server code?
Any help is appreciated, thanks!