我的猫鼬有问题。我尝试使用Schema方法设置两个属性,但是它们根本不会保存。
用户模型
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const crypto = require("crypto");
const UserSchema = new Schema({
email: {
type: String,
unique: true,
required: true
},
password: {
type: String
},
salt: String
});
UserSchema.methods.passwordHash = password => {
this.salt = crypto.randomBytes(16).toString("hex");
this.password = crypto
.pbkdf2Sync(password, this.salt, 1000, 64, "sha512")
.toString("hex");
};
...
module.exports = User = mongoose.model("user", UserSchema);
我从meteor create project failing
获得了 passwordHash 方法Index.js
const User = require("../../models/User");
...
const newUser = new User();
newUser.email = email;
newUser.passwordHash(password);
newUser.save(err => {
if (err) return res.send({ message: "Server error" });
});
我得到的是:
答案 0 :(得分:0)
我发现了问题-我使用了箭头功能,所以这是指原始上下文,而不是当前模型:
UserSchema.methods.passwordHash = function(password) {
this.salt = crypto.randomBytes(16).toString("hex");
this.password = crypto
.pbkdf2Sync(password, this.salt, 1000, 64, "sha512")
.toString("hex");
};