9

担当者 (ユーザー) を認証するために、Mongoose でインスタンス メソッドを定義しました。

RepSchema.methods.authenticate = function(password){
  return this.encryptPassword(password) === this.hashed_password;
};

私のアプリでは、担当者を見つけてそのauthenticateメソッドを呼び出します。

var mongoose = require("mongoose");
var Rep = mongoose.model("Rep");

Rep.findOne({email: email}, function(err, rep){
  if (rep.authenticate(req.body.session.password)){
    req.session.rep_id = rep._id;
    res.redirect('/calls', {});
  }
});

ただし、次のエラーが表示されます。

TypeError: Object { email: 'meltzerj@wharton.upenn.edu',
  password: XXXXXXXXX,
  name: 'meltz',
  _id: 4fbc6fcb2777fa0272000003,
  created_at: Wed, 23 May 2012 05:04:11 GMT,
  confirmed: false,
  company_head: false } has no method 'authenticate'

私は何を間違っていますか?

4

1 に答える 1

16

それで、私はついに自分が間違っていたことを理解しました。schema.methodsMongoose ソース コードは、モデルのスキーマがモデル名 ( ) に設定された時点で、内部で定義されたすべてのメソッドをモデルのプロトタイプに適用しますmongoose.model("modelname", modelSchema)。したがって、モデルをその名前に設定する前に、これらのメソッドを Schema インスタンスのメソッド オブジェクトに追加するすべてのメソッドを定義する必要があります。メソッドを定義する前にモデルを設定していました。問題が解決しました。

于 2012-05-23T21:50:19.193 に答える