DEV Community

Cover image for MongoDB for Express.js
Edwin
Edwin

Posted on

MongoDB for Express.js

Persistence.
Persistence in nodejs basically means a way of storing data.It can be in any of the 3 ways:

  • FileSystem
  • Cloud
  • Database

Filesystem is not secure at all when it comes to deploying your web app to the online world.

Cloud persistance is becoming more popular.I would basically recommend Mongo Atlas (what is been called Mongo on the cloud).It is more secure and inexpensive.It's free for simple applications.

Database persistence has been there for years,mainly on relational databases such as MySQL ,Oracles,Postgres etc.NoSQL databases such as mongodb,cassandra and couch are currently challenging RDBMS.Mongodb is more popular that's why it is a good start.

Create a models folder.Inside it ,create a users.js file.Now ,we will have to install an Object document mapper for mongodb.In this case,it's mongoose.Install it:

npm install --save mongoose

Mongoose introduces schemas and models.When combined ,it is similar to object-oriented programming.

const mongoose = require("mongoose");

//create a schema
var userSchema = mongoose.Schema({
      name: String,
      email:String,
      password : String,
      date:Date,
});

//create a model
var User = mongoose.model("User",userSchema);

module.exports = User;
Enter fullscreen mode Exit fullscreen mode

Now let's head over to our main app.js and introduce our database and save each item(name & password) to the database.

//import the express module
const express = require("express");
const app = express();
//body-parser middleware
app.use(require("body-parser")());

//link mongoose and connect
const mongoose = require("mongoose");
mongoose.connect('mongodb://localhost/webApp', {useNewUrlParser: true});

//link the user model
var User = require("./model/user");



//set up handlebars
const handlebars = require('express3- handlebars')
              .create({defaultLayout:'main'});
app.engine('handlebars',handlebars.engine);
app.set('view engine','handlebars');

//set the port number to listen on
app.set('port',process.env.PORT || 8080);

//our slash route will render the home view
app.get('/',(req,res)=>{
    res.render('home');
});

//get user input and display it
app.post("/process",(req,res)=>{
        const name = req.body.name;
        const email= req.body.email;
        const password = req.body.password;

        User = new User({
            name:name,
            email:email,
            password:password
        });
        User.save(user,err)
        .then(user=>console.log('saved'))
        .catch(err=> console.log(err));
});

//our about route will render the about view
app.get('/about',(req,res)=>{
    res.render('about');
});

//create a callback for listening on the server
app.listen('port',()=>{
    console.log(`Listening on port ${app.get('port')}.Press CTRL Z to cancel.`);
}):
Enter fullscreen mode Exit fullscreen mode

Done!
As you have seen,I haved the user and logged that in my console,but what happens thereafter is redirect the user to the login page if you have one.
The new user's details have been saved.Great day all!

Top comments (0)