如何在mongoose中访问附加到Schema的方法

时间:2016-02-02 09:35:05

标签: node.js mongodb mongoose 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);

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

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

    return bcrypt.compareAsync(submittedPassword, savedPassword);
  }

我尝试验证这样的密码:

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

          return vendor.verifyPassword(password);
        });

如果这有任何区别,我已经宣布了与蓝鸟承诺的猫鼬。我已经尝试了很多东西,但是当我尝试调用我认为已经附加了模式的方法时,找不到任何关于为什么没有发生任何问题的答案。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

/*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);

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

/*anotherfile.js*/
var VendorSchema= require('../VendorSchema.js');
var Vendor = new VendorSchema();

当我们将method2定义为static时,您可以使用schemareference对象VendorSchema访问anotherfile.js中的method2。

VendorSchema.method2

但是method1不是静态的,你只能在创建schema的对象实例之后才能访问anotherfile.js中的method1。

Vendor.method1 /*Vendor is object instance of the schema*/