如何访问附加到猫鼬模式的方法

tbe*_*en1 3 mongoose mongodb node.js mongoose-schema

我在调用我正在处理的项目中附加到架构的方法时遇到一些困惑。我本质上是从数据库访问文档,并尝试将我存储的散列密码与用户在登录时提交的密码进行比较。然而,当我尝试比较密码时,我附加到模式的方法对象的方法却找不到。它甚至不会向我抛出错误,告诉我没有这样的方法。这是我在架构上设置方法的地方:

var Schema = mongoose.Schema;

var vendorSchema = new Schema({
  //Schema properties
});

vendorSchema.pre('save', utils.hashPassword);
vendorSchema.methods.verifyPassword = utils.verifyPassword;

module.exports = mongoose.model('Vendor', vendorSchema);
Run Code Online (Sandbox Code Playgroud)

我用作比较方法的函数是我创建的实用程序函数,名为 verifyPassword,它保存在实用程序文件中。该函数的代码在这里:

verifyPassword: function (submittedPassword) {
    var savedPassword = this.password;

    return bcrypt.compareAsync(submittedPassword, savedPassword);
  }
Run Code Online (Sandbox Code Playgroud)

我尝试像这样验证密码:

    var password = req.body.password;
    _findVendor(query)
        .then(function (vendor) {

          return vendor.verifyPassword(password);
        });
Run Code Online (Sandbox Code Playgroud)

我已经向猫鼬承诺了蓝鸟的承诺,如果这有什么区别的话。我已经尝试了很多方法,但找不到任何答案来解释为什么当我尝试调用这个我认为已附加架构的方法时什么也没有发生。任何帮助将不胜感激。

nul*_*941 5

/*VendorSchema.js*/
var Schema = mongoose.Schema;
var vendorSchema = new Schema({
  //Schema properties
});
vendorSchema.methods.method1= function{
         //Some function definition
};
vendorSchema.statics.method2 = function{
         //Some function definition
};
module.exports = mongoose.model('Vendor', vendorSchema);
Run Code Online (Sandbox Code Playgroud)

假设我想访问其他文件中的 VendorSchema:

/*anotherfile.js*/
var VendorSchema= require('../VendorSchema.js');
var Vendor = new VendorSchema();
Run Code Online (Sandbox Code Playgroud)

由于我们将 method2 定义为静态,您可以使用 schemareference 对象 VendorSchema 访问 anotherfile.js 中的 method2。

VendorSchema.method2
Run Code Online (Sandbox Code Playgroud)

但 method1 不是静态的,您只能在创建模式的对象实例后才能使用 anotherfile.js 中的 method1 进行访问。

Vendor.method1 /*Vendor is object instance of the schema*/
Run Code Online (Sandbox Code Playgroud)