Build a Basic M.E.N. Site - 2 - MongoDB Connection
I set up the basic server in the previous article, now we need to connect it to a database to store datas for the site.
Connect to MongoDB
Use your Mongo to memorize
Install that Mongo
npm install mongodb --save
Connect to MongoDB through MongoClient
const MongoClient = require("mongodb").MongoClient
MongoClient.connect("LINK-TO-MONGODB", function(err, database) {
/// ... start the server
}Need a DB to connect to.
I will just follow the tutorial to create a DB on mLab. It is now aquiered by mongoDB Inc. and called MongoDB Atlas.
Create a user and it’s password, find the url to connect to the DB.
(I still have questions about the security since the user and password are all writen inside the server.js file. Seems like the security is done by granting different rights to different users, but not really clear for me now.)Start server only when database is connected:
var db
MongoClient.connect("LINK-TO-MONGODB", function(err, client){
if (err) return console.log(err
db = client.db("DBNAME")
app.listen(3000, function(){
console.log("listening on 3000")
})
})
Create collection to store stuff
- Under the app.post method, specify a collection by calling db.collection() method. If the collection doesn’t exist then
db.collection()
function will create it.
After creating/chosing the collection, we usedb.collection().insertOne()
function to CREATE(insert) data.
VERY IMPORTANT! We have throw a signal to tell the application to redirect to the root directory by useingres.redirect()
so that the server knows that this action is finished:app.post("/plusorminus", function(req, res) {
db.collection("plusorminus").insertOne(req.body,function(err, result){
if (err) return console.log(err)
res.redirect("/");
})
})
Add some logic to handle different user inputs
Avoid duplication
Since I only want one vote for one user, I use.findOne()
to look for an user name, and put the.insertOne()
under an if/else statement.
And the whole POST block will look like this:if(user){
console.log(req.body.FacebookName + " already exist.")
res.redirect("/")
}Check for empty entry:
if(req.body.FacebookName == ""){
console.log("Please enter your name.")
res.redirect("/")
}Trim the TOO LONG NAME
if (req.body.FacebookName.length > 20){
req.body.FacebookName = req.body.FacebookName.substring(0,20)
}
And the final .post
section will look like this:
app.post("/plusorminus",function(req, res){ |
Here is a web site with a simple CREATE(input) functionality. Next we will look at how to READ data from the database and show them to the users.