2017-11-23 4 views
0

사용자가 DB에 생성되었습니다. 코드가 여러 번 검사되고 구문 오류가 없으며 사용자가 생성 되어도 정의되지 않은 값만 반환됩니다. 이름과 비밀번호로 게시물을 요청할 때 자격 증명을 올바르게 입력하십시오. 코드 :mongoDB에서 찾을 수없는 사용자를 인증 할 수 없습니다.

var mongoose = require("mongoose"); 
    var Schema = mongoose.Schema; 

var User = new Schema({ 
     name: String, 
     password: String, 
    admin: Boolean 
}); 

var Usermodel = mongoose.model("user", User); 
module.exports = Usermodel; 

router.post('/authenticate', function(req, res) { 

    // find the user 
    user.findOne({ 
    name: req.body.name 
    }).then(function(err, user) { 
    console.log(user); 
    if (err) throw err; 

    if (!user) { 
     res.json({ success: false, message: 'Authentication failed. User not found.' }); 
    } else if (user) { 

     // check if password matches 
     if (user.password != req.body.password) { 
     res.json({ success: false, message: 'Authentication failed. Wrong password.' }); 
     } else { 

     // if user is found and password is right 
     // create a token with only our given payload 
    // we don't want to pass in the entire user since that has the password 
    const payload = { 
     admin: user.admin 
    }; 
     var token = jwt.sign(payload, 'superSecret', { 
      expiresIn: 60*60*24 // expires in 24 hours 
     }); 

     // return the information including token as JSON 
     res.json({ 
      success: true, 
      message: 'Enjoy your token!', 
      token: token 
     }); 
     } 

    } 

    }); 
}); 

모든 의존성이 필요합니다, 나는 문이 정의되지 않은 내가 만든 사용자와 CONSOLE.LOG 수익을 찾을 수없는 단지 경우, 콘솔에 오류를하지 않습니다. 내가 뭔가를 놓친거야? 이것은 의미가 없습니다. 나는 콜백을 약속으로 바꾸었고 여전히 동일하다. 나는 DB에서 사용자를 찾을 때 뭔가 잘못하고있는 것처럼 느낍니다. 나는 find ({})를 시도했지만 운이 없었다.

+0

당신이 몽고 콘솔에서 찾을 수 있어야한다? –

+1

약속 기반 mongoose findOne에서, 당신은 then 절에서만 문서를 얻습니다. 또한 exec()를 사용하는 것이 좋습니다. – tumulr

+0

@MustafaMamun 저는 Mongo 콘솔 대신 Robo 3T를 사용하고 있습니다. 그렇지만 콘솔에서도 볼 수 있습니다. – Limpuls

답변

0

user.find를 사용하고 있으므로 사용자 변수는 무엇입니까? 어디에서 선언 했습니까?

당신은 Usermodel에 사용자 스키마 모델을 할당하는

귀하의 질의는 Usermodel.findOne({name:req.body.name})

+0

Usermodel은 user.js라는 파일에 있기 때문에 api.js 라우트 문서에이를 요구하고이를 user variable에 할당합니다. 그게 바로 사용자가오고있는 곳입니다. – Limpuls

+0

잘못된 변수를 사용하면 정의되지 않은 오류가 발생할 것이라고 생각합니다. 이제 다음과 같이 보입니다 :'var user = require ("../ models/user");' – Limpuls