How to make user registration with Node.js and MongoDB (using mongoose and Express.js)

37,631

Maybe you should consider Passport or another module. But you can do something like this:

app.post('/signup', function (req, res, next) {
    var user = {
       Name: req.body.name,
       Email: req.body.email,
       Pass: req.body.pass,
       Num: req.body.num
   };
   var UserReg = mongoose.model('UserReg', RegSchema);
   UserReg.create(user, function(err, newUser) {
      if(err) return next(err);
      req.session.user = email;
      return res.send('Logged In!');
   });
});

app.post('/login', function (req, res, next) {
   var email = req.body.email;
   var pass = req.body.pass;

   User.findOne({Email: email, Pass: pass}, function(err, user) {
      if(err) return next(err);
      if(!user) return res.send('Not logged in!');

      req.session.user = email;
      return res.send('Logged In!);
   });
});

app.get('/logout', function (req, res) {
   req.session.user = null;
});

Then you should have a middleware to handle authentication

function isLoggedIn (req, res, next) {
  if (!(req.session && req.session.user)) {
    return res.send('Not logged in!');
  }
  next();
}

And use it on the private routes

app.get("/api", isLoggedIn, function (req, res) {
   //Something private
})
Share:
37,631
Vatex Official
Author by

Vatex Official

Updated on October 24, 2020

Comments

  • Vatex Official
    Vatex Official over 3 years

    I need your help. I want to make User registration form and use Nodejs, Express.js, MongoDB(mongoose) and give me very simple example how to make user registration form with: Name, Email, Password and Mobile Number :) I've made mongoose schema and give values like that Name: req.body.name but it won't work :/ In my oppinion I made something bad.

    this is my code and if you think it's not correct, please correct it. (sorry for my bad english). this is server.js

    var mongoose = require('mongoose');
    mongoose.connect('mongodb://localhost/addressbookdb');
    var express = require('express');
    var app = express();
    var db = mongoose.connection;
    
    app.use(express.static(__dirname + '/../client'));
    
    app.post("/",function(req,res){
        res.end("Registration Succesfully Completed!");
    
        var db = mongoose.connection;
        db.on('error', console.error.bind(console, 'connection error:'));
        db.once('open', function (callback) {
            console.log("connected.")
        });
    
        // Schema
        var RegSchema = mongoose.Schema({
            Name: String,
            Email: String,
            Pass: String,
            Num: Number,
            reg_time : {
                type : Date, default: Date.now
            }
        }, { collection: 'AddressCol' });
    
        // Model
        var UserReg = mongoose.model('UserReg', RegSchema);
    
        // Add in collection
        var UserAdd = new UserReg({
            Name: req.body.name,
            Email: req.body.email,
            Pass: req.body.pass,
            Num: req.body.num,
        });
    
        // Save
        UserAdd.save(function (err, fluffy) {
            if (err) return console.error(err);
        });
    });
    
    app.listen(8000, function() {
      console.log("Server is running!");
    });
    

    and this is my HTML page:

    <div class="form-group">
        <input type="text" class="form-control" id="name" placeholder="name><br>
        <input type="email" class="form-control" id="email" placeholder="Email"><br>
        <input type="password" class="form-control" id="pass" placeholder="Password"><br>
        <input type="number" class="form-control" id="num" placeholder="Number"><br>
        <button type="submit" class="btn btn-primary" id="reg-form-btn">Registration!</button>
    </div>
    <script>
        $(document).ready(function() {
            $("#reg-form-btn").click(function() {
                var name = $("#name").val();
                var email = $("#email").val();
                var pass = $("#pass").val();
                var num = $("#num").val();
                $.post("/", {
                    Name: name,
                    Email: email,
                    Pass: pass,
                    Num: num
                });
            });
        });
    </script>