猫鼬:不使用方法保存this.property

时间:2018-08-06 17:30:13

标签: javascript node.js mongodb mongoose

我的猫鼬有问题。我尝试使用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" });        
});

我得到的是:

this tutorial

1 个答案:

答案 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");
};