DEV Community

Cover image for MongoDB for Express.js

Posted on

MongoDB for Express.js

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,
      password : String,

//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

//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')
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

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

        User = new User({
        .catch(err=> console.log(err));

//our about route will render the about view

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

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)