0

expressjsとmongodbを使用して物事を検証する際にいくつかの問題が発生しています。

これはコメントされたクラスです

// mongodb configuration
var Server = require('mongodb').Server,
  Db       = require('mongodb').Db,
  ObjectID = require('mongodb').ObjectID,
  server   = new Server('localhost',27017,{auto_reconnect:true}),
  db       = new Db('fantacalcio',server);
// mongodb end configuration


var UserModel = function() {

  // max and min username length
  this.username_max = 15;
  this.username_min = 6;
};

// create funcion
UserModel.prototype.create = function(req,callback) {

  // opening connection
  db.open(function(err,db){
    if(!err){

      // choosing the collection
      db.collection('user',function(err,collection){
          if(err){
            console.log(err);
          }
          else{

            // Passing the req.body data and a callback to the validate function (see below) 
            this.validate(req,function(results){

              // if the validate function return true, this will insert the username into the db
              if(results==true){
                collection.insert({username : req.body.username}, function(err,result){
                  if (!err) {
                    db.close();
                    callback(200);
                  }
                }); 
              }
              else{
                callback(results);
              }
            });
          }
      });
    }
  });

};


// validating function
UserModel.prototype.validate = function(req,callback) {

  var errors=0;
  var detail_error;
  var username = req.body.username;

  // check the username
  if(!username || username < this.username_min || username>this.username_max){
    errors++;
    detail_error +="this is an error";
  }

  // will execute the callback witin the error
  if(errors>0){
    callback(detail_error);
  }

  // if there arent error will return true
  else{
    callback(true);
  }
};

私が得るエラーは

TypeError: Object #<Object> has no method 'validate'

次の行を参照してください。

 this.validate(req,function(results){ .......
4

1 に答える 1

1

問題の行はコールバックの一部として実行されるため、コールバックが呼び出されたときにインスタンスthisを参照することはありません。UserModelの最初の行では、変数 (通常は と呼ばれますが、一部の人は を好みます)UserModel.prototype.createを宣言し、それに代入する必要があります。次に、コールバック内のすべてのケースをそれに置き換えます。selfthatthisthis

これthisは実際には変数ではなくキーワードであり、クロージャでは変数のように動作しないことに注意してください。その値をクロージャーに保存したい場合は、それを実際の変数にコピーする必要があります。

于 2012-08-16T16:44:40.733 に答える