2016-12-07 33 views
3

我想知道是否有辦法讓用戶用戶名或電子郵件登錄 我搜索了很多次,但沒有找到工作方法。我沒有一個想法如何做到這一點,請儘可能以最簡單的方式提供幫助。這裏是我的用戶架構看起來像:通過電子郵件或用戶名與Node.js中的MongoDB登錄

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); 

其他信息:我正在nodejs頂部工作。 任何幫助都非常感謝。 thnx

+0

您應該嘗試自行尋找解決方案併發布您嘗試過的方法。你不應該要求完整的解決方案,並讓別人做你的工作。 – Syc

回答

4
//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 
     }; 
    } 
    elseif(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(); 
}; 
+2

這正是我所需要的。 thnx人,你是天使 – Zub

相關問題