node.jsmongodbmongoosemongoose-schemamongoose-populate

login with email or username with MongoDB in Node.js


I am wondering if there is a way to let user to login with both username or email I searched a lot of times for but doesn't found a working method. I don't have a single idea how to do this, please help with the easiest way if possible. here is what my user schema looks like :

var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");

var UserSchema = new mongoose.Schema({
    fullname: String,
    username: { type : String , lowercase : true , unique: true ,  required: true, minlength: 3, maxlength: 10},
    email: String, 
    password: String,
    mobile: String,
    gender: String,
    profession: String,
    city: String,
    country: String,
    joining: {type: Date, default: Date.now}
});

UserSchema.plugin(passportLocalMongoose);

module.exports = mongoose.model("User", UserSchema);

Addition info: I am working on top of nodejs. Any help is seriously appreciated. thnx


Solution

  •  //the simple example of login// 
     router.post('/users/login', function(req, res) {
         var users = req.app;
         var email = req.body.email;
         var password = req.body.password;
         var username = req.body.username;
         var data;
         if (email.length > 0 && password.length > 0) {
             data = {
                 email: email,
                 password: password
             };
         }
         else if(username.length > 0 && password.length > 0) {
             data = {
                 username: username,
                 password: password
             };
         } else {
             res.json({
                 status: 0,
                 message: err
             });
         }
         users.findOne(data, function(err, user) {
             if (err) {
                 res.json({
                     status: 0,
                     message: err
                 });
             }
             if (!user) {
                 res.json({
                     status: 0,
                     msg: "not found"
                 });
             }
             res.json({
                 status: 1,
                 id: user._id,
                 message: " success"
             });
         })
     } else {
         res.json({
             status: 0,
             msg: "Invalid Fields"
         });
     }
     });
    
     //and if you have to create schema 
    
     var db_schema = new Schema({
         email: {
             type: String,
             required: true,
             unique: true
         },
         password: {
             type: String,
             required: true,
             unique: true
         },
     });
     // define this in your db.js
     var login_db = mongoose.model('your_db_name', db_schema);
     return function(req, res, next) {
         req.app = login_db;
         next();
     };