Save form data to MongoDB with NodeJS
Intro
In this tutorial we will create simple form that will save user data to server implemented in Node.js with MongoDB database and allow us to see saved data on a separate page in JSON format.
Prerequisites
1. Install MongoDB
It depends on your environment how to install and configure MongoDB. We use Cloud9 for this tutorial, so will refer to the manual on the official website.
In the bash command line we will issue the following commands:
sudo apt-get install -y mongodb-org
mkdir data
echo 'mongod --bind_ip=$IP --dbpath=data --nojournal --rest "$@"' > mongod
chmod a+x mongod
./mongod
2. Install required packages
We will use Node.js with the following packages:
- Express - popular web framework;
- body-parser - body parser middleware, allows
to access
req.body
property; - mongodb - MongoDB driver for Node.js
In the command line we will use following commands:
npm init -y
npm i --save express body-parser mongodb
Create form
We will create file named index.html
in the folder public
:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Client Data</title>
</head>
<body>
<h1>Please fill data in the form below:</h1>
<form method="POST" action="/post-feedback">
<label>Name:<input type="text" name="client-name" required></label>
<br>
<label>Email:<input type="text" name="client-email" required></label>
<br>
<label>Comment:<br><textarea name="comment"></textarea></label>
<br>
<input type="submit" value="Submit">
</form>
<a href="/view-feedbacks">View feedbacks</a>
</body>
</html>
Create app.js
code
1. Create initial code to serve static content
var express = require('express');
var path = require('path');
var app = express();
app.use(express.static(path.resolve(__dirname, 'public')));
app.listen(process.env.PORT || 3000, process.env.IP || '0.0.0.0' );
2. Add connection to database
We will modify previous code and add connection to database:
var express = require('express');
var path = require('path');
var mongodb = require('mongodb');
var dbConn = mongodb.MongoClient.connect('mongodb://localhost:27017');
var app = express();
app.use(express.static(path.resolve(__dirname, 'public')));
app.listen(process.env.PORT || 3000, process.env.IP || '0.0.0.0' );
3. Add handler for form post
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var mongodb = require('mongodb');
var dbConn = mongodb.MongoClient.connect('mongodb://localhost:27017');
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.resolve(__dirname, 'public')));
app.post('/post-feedback', function (req, res) {
dbConn.then(function(db) {
delete req.body._id; // for safety reasons
db.collection('feedbacks').insertOne(req.body);
});
res.send('Data received:\n' + JSON.stringify(req.body));
});
app.listen(process.env.PORT || 3000, process.env.IP || '0.0.0.0' );
4. Add handler for data view
Our final code will look like this:
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var mongodb = require('mongodb');
var dbConn = mongodb.MongoClient.connect('mongodb://localhost:27017');
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.resolve(__dirname, 'public')));
app.post('/post-feedback', function (req, res) {
dbConn.then(function(db) {
delete req.body._id; // for safety reasons
db.collection('feedbacks').insertOne(req.body);
});
res.send('Data received:\n' + JSON.stringify(req.body));
});
app.get('/view-feedbacks', function(req, res) {
dbConn.then(function(db) {
db.collection('feedbacks').find({}).toArray().then(function(feedbacks) {
res.status(200).json(feedbacks);
});
});
});
app.listen(process.env.PORT || 3000, process.env.IP || '0.0.0.0' );
Final words
This tutorial was created as minimal possible demo to show the concept of sending form to the server and saving it to MongoDB. It is not intended for production use because it does not handle errors and has not implemented security.
Source code
Link to repository: https://github.com/programmingmentor/form-nodejs-mongodb