jas0nhuang

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

  1. Install that Mongo

    npm install mongodb --save
  2. Connect to MongoDB through MongoClient

    const MongoClient = require("mongodb").MongoClient

    MongoClient.connect("LINK-TO-MONGODB", function(err, database) {
    /// ... start the server
    }
  3. 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.)

  4. 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

  1. 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 use db.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 useing res.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

  1. 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("/")
    }
  2. Check for empty entry:

    if(req.body.FacebookName == ""){
    console.log("Please enter your name.")
    res.redirect("/")
    }
  3. 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){
db.collection("plusorminus").findOne({FacebookName:req.body.FacebookName}, function(err, user){
console.log(req.body.FacebookName)
if(req.body.FacebookName == ""){
console.log("Please enter your name.")
res.redirect("/")
}
else if(user){
console.log(req.body.FacebookName + " already exist!")
res.redirect("/")
}
else {
if (req.body.FacebookName.length > 20){
req.body.FacebookName = req.body.FacebookName.substring(0,20)
}
db.collection("plusorminus").insertOne(req.body, function(err, result){
if (err) return console.log(err)
res.redirect("/")
console.log("Thank you for your vote!")
})
}
})
})

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.