사용자가 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 ({})를 시도했지만 운이 없었다.
당신이 몽고 콘솔에서 찾을 수 있어야한다? –
약속 기반 mongoose findOne에서, 당신은 then 절에서만 문서를 얻습니다. 또한 exec()를 사용하는 것이 좋습니다. – tumulr
@MustafaMamun 저는 Mongo 콘솔 대신 Robo 3T를 사용하고 있습니다. 그렇지만 콘솔에서도 볼 수 있습니다. – Limpuls