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

이것은 내가 필요한 것입니다. 너는 천사 야. – Zub

관련 문제