2016-07-15 1 views
0

usersSchema에 해시 된 암호를 내 hash 필드에 설정하고 싶습니다. 스키마는 다음과 같습니다.몽구스 스키마 메서드 및 "this"updates 속성 - NodeJS

// models/user-model.js 

const usersSchema = new Schema({ 
    name: { 
    type: String, 
    required: true 
    }, 
    email: { 
    type: String, 
    unique: true, 
    required: true 
    }, 
    hash: String, 
    salt: String 
}, { timestamps: true }); 

usersSchema.methods.setPassword = (password) => { 
    this.salt = crypto.randomBytes(16).toString('hex'); 
    this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex'); 
}; 

내 경로에서 이름, 전자 메일 및 비밀번호로 새 사용자를 설정하려고합니다. {이름 : '야곱'이메일 '[email protected]'} I 경로에서 console.log(user), 그것은 나에게 다음과 같은 줄 때

// routes/users.js 

router.get('/setup', (req, res) => { 
    const user = new User(); 

    user.name = 'Jacob'; 
    user.email = '[email protected]'; 

    user.setPassword('password'); 

    user.save() 
    .then((user) => { 
     const token = user.generateJwt(); 
     res.json({ yourToken: token }); 
    }) 
    .catch((err) => { 
     res.json(err); 
    }); 
}); 

가 :

을 나는 알고 여기에 경로입니다 setPassword 방법은 적절한 해시를 만드는 데까지 적용됩니다. 그러나 해당 해시는 user 개체에 저장하지 않습니다. 및 hash 속성을 설정할 수 있도록 개체에 setPassword을 어떻게 적용합니까?

답변

2

굵은 화살표 표기법을 사용하면 thissetPassword에서 참조하는 내용을 변경하므로 더 이상 사용자 문서를 가리 키지 않습니다. 일반 함수 선언을 사용하여

시도 :

usersSchema.methods.setPassword = function(password) { 
    this.salt = crypto.randomBytes(16).toString('hex'); 
    this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex'); 
}; 
+0

허. 확실히 알지 못했습니다. 그러나 확실히, 그것은 효과가 있었다! 이 글을 읽은 다른 사람들을 위해 [그 대답] (https://www.nczonline.net/blog/2013/09/10/understanding-ecmascript-6-arrow-functions/)에 대한 자세한 내용을 읽었습니다. – Jacob