私は、Node.jsにbcryptを使用してパスワードを暗号化しています。また、MongoDBを使ってMongoDBデータベースとユーザーモデルを作成しています。node.bcrypt.jsがオブジェクト内のパスワードを更新しない
ただし、データがI GET
(Postmanを使用)の場合は、平文パスワードがパスワードハッシュに更新されていません。ここに私のコードは次のとおりです。
user.jsの:
const userSchema = new mongoose.Schema({
"email": { type: String, required: true, unique: true, trim: true },
"username": { type: String, required: true, unique: true },
"name": {
"first": String,
"last": String
},
"password": { type: String, required: true },
"created_at": { type: Date, default: Date.now },
"updated_at": { type: String }
})
userSchema.pre("save", function(next) {
var user = this
if (!user.isModified('password')) return callback()
bcrypt.genSalt(10, function(err, salt) {
if (err) return next(err)
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) return next(err)
user.password = hash
console.log(user.password)
})
})
const currentDate = new Date
user.updated_at = currentDate
next()
})
const User = mongoose.model("users", userSchema)
export default User
は、ユーザーデータを投稿:私は、データを取得するとき
router.route("/users").post((req, res) => {
let json = {}
const newUser = new User({
username: req.body.username,
email: req.body.email,
name: {
first: req.body.firstName,
last: req.body.lastName
},
password: req.body.password
})
newUser.save((err) => {
if (err) {
json.error = err.message
} else {
json.id = newUser._id
}
res.json(json)
})
})
を私は上記に述べたように、エラーがないパスワードがまだあります単純な平文ではなく、ハッシュです。関数内でconsole.log(user.password)
を使用すると、ハッシュが返されます。
私はちょうどバックエンドのものを学び始めました(私はフロントエンドの開発者です)ので、アドバイスをいただければ幸いです。ありがとうございます!
あなたがフィニッシュにbcryptのを待っていません。コールバックでそれを行う必要があります。 – SLaks