7

这是我的 users.js 模型。

var mongoose = require('mongoose')
  , crypto = require('crypto')
  , mongoTypes = require('mongoose-types');

mongoTypes.loadTypes(mongoose, 'email');
mongoose.connect('mongodb://localhost/popbroker');

function hash1 (msg, key) { 
  return crypto.createHmac('sha256', key).update(msg).digest('hex');
};

function required(val) { return val && val.length; }

var Schema = mongoose.Schema
  , ObjectId = Schema.ObjectId;

var UserSchema = new Schema({
    username: {
      type: String,
      validate: [required,"Username is required"],
      index: {unique: true}
    },
    email: {
        type: mongoose.SchemaTypes.Email,
        validate: [required, 'Email required'],
        index: { unique: true }
    },
    password: {
        type: String,
        validate: [required, 'Password required'],
    },
    socialauth:{
      type:String,

    createdAt: {
        type: Date,
        'default': Date.now
    }
});


var UserApiSchema = new Schema({
    user :ObjectId,
    apiKey: {
        type: String,
        validate: [required, 'Senha é obrigatório'],
    },
    createdAt: {
        type: Date,
        'default': Date.now
    }
});


UserSchema.path('email').validate(function (v, fn) {
    User.count({email: v}, function (err, val) {
        if (err) fn(false);
        fn(val==0);
    });
}, 'Email exists!'); 

UserSchema.path('username').validate(function(v,fn){
  User.count({username:v},function(err,val){
    if(err) fn(false);
    fn(val==0);
  });
},'Username exists');

UserApiSchema.path('apiKey').validate(function(v,fn){
  UserApi.count({apiKey:v},function(err,val){
    if(err) fn(false);
    fn(val == 0);
  });
}, 'Api Key wrong');


UserSchema.statics.authenticate = function (email, password, fn) {
    this.findOne({email: email}, function (err, user) {
        if (!user) return fn(new Error('cannot find user'));
        if (user.password == hash1(password, conf.secret)) return fn(null, user);
        // Otherwise password is invalid
        fn(new Error('invalid password'));
    })
;};

UserApiSchema.statics.createApi = function(user,fn){
  var instance = new UserApi();
  instance.user = user;
  instance.apiKey = "asdasdacas121213dasasd";
  console.log("username is " + user.username);
  instance.save(function(err){
    fn(err,instance);

  });
};


UserSchema.statics.getUser = function(userid){
  var user = mongoose.model('User', UserSchema);
  var query = user.findOne({'_id':userid})
  query.exec(function (err, user) {
  if (err) return handleError(err);
  console.log(user.username);
  return user;
});
}


UserApiSchema.statics.getUser = function(apiKey,fn){
  var usAp = UserApiSchema
  var userApi = mongoose.model('UserApi', UserApiSchema);
  var user = mongoose.model('User', UserSchema);
  var query = userApi.findOne({ 'apiKey': apiKey });


  query.exec(function (err, userApi) {
  if (err) return handleError(err);
  console.log(userApi.user);
  user = user.getUser(userApi.user);
  fn(err, userApi);;// Space Ghost is a talk show host.
});
};

UserSchema.statics.newUser = function (email, password,username, fn) {
    var instance = new User();
    var apiInstance = new UserApi();
    instance.email = email;
    instance.password = require('crypto').createHash('sha256').update(password).update('salt').digest('hex');
    instance.username = username;

    instance.save(function (err) {
        fn(err, instance);
    });
};

UserSchema.statics.resetPassword = function(userId, callback) {
    var newPassword = '';
    newPassword = newPassword.randomString(6);
    var cripto = password;
    var data = {} 
        data.password = crypto;

    this.update({_id: userId}
        , {$set: data}
        , {multi:false,safe:true}
        , function( error, docs ) {
            if (error) {
                callback(error);
            }
            else {
                callback(null, newPassword);
            }
        });
}


var LinkSchema = new Schema({

  user: ObjectId,

  text: {
      type: String,
      validate: [required,"Text is required"],
      index: {unique: true}
    },
    body: {
        type: String,
        validate: [required, 'Body is required'],
        index: { unique: true }
    },
    createdAt: {
        type: Date,
        'default': Date.now
    }
})

/*
Exporting findByid function to return back a link based on an id.
*/

LinkSchema.statics.newLink = function (text, body,user, fn) {
    var instance = new Link();
    instance.text = text;
    instance.body =body;
    instance.user = user;

    instance.save(function (err) {
        fn(err, instance);
    });
};


/*
Export findAll function to return back all the links. 
*/

exports.findAll = function(req,res){
  console.log("Retrieving all the links");
  db.collection('links',function(err,collection){
    collecction.find().toArray(function(err,items){
      res.send(items);

    });
  });
};



Link = mongoose.model('Link', LinkSchema);

exports.Link = Link;


User = mongoose.model('User', UserSchema);
UserApi = mongoose.model('UserApi',UserApiSchema);
exports.UserApi = UserApi;
exports.User = User;

由于我是 nodejs 新手,因此很难理解此错误的含义或发生原因。因此,错误是什么意思以及如何摆脱它?

编辑:这是我的 newUser 电话。

app.post(
        '/signup/',
        function(req, res) {
             {console.log(req.body.username);
                User.newUser(

                    req.body.email, req.body.password,req.body.username,req.body.apiKey,"pocket",
                    function (err, user) {
                        if ((user)&&(!err)) {
                            console.log(user.username)

                            UserApi.createApi(
                                    user,function(err,userapi){
                                        if((!err)){
                                            console.log("Api created");
                                            res.send("APi created");

                                        }
                                        else{
                                            if(err.errors.apiKey){
                                                res.send(err);
                                            }
                                        }


                                    });
                            req.session.regenerate(function(){
                                req.session.user = user._id;
                                //res.send("Success here!"); 

                            });
                        } else {
                            if (err.errors.email) {
                              res.send(err) 
                              console.log(req.body.password);
                              console.log(req.body.email);
                              console.log(req.body);
                            }                           
                           if (err.errors.username) {
                              res.send(err) 
                              console.log(req.body.password);
                              console.log(req.body.email);
                              console.log(req.body);
                            }   
                        }
                    });


            } 
        });
4

1 回答 1

7

通过您的编辑,您传递的参数比newUser预期的要多。这导致fn设置 的值req.body.apiKey,这显然是undefined

UserSchema.statics.newUser = function (email, password, username, fn) {
    // ...
});

User.newUser(               // set to...
    req.body.email,         // => email
    req.body.password,      // => password
    req.body.username,      // => username
    req.body.apiKey,        // => fn
    "pocket",               // => (unnamed), arguments[4]
    function(err, user) {   // => (unnamed), arguments[5]
        // ...
    }
});

您要么想要编辑函数以命名其他参数,要么在实际上不需要它们时将它们从调用中删除(因为您在预期的回调UserApi内部和内部都创建了一个实例)。newUser


[原来]

该错误意味着您正在尝试调用undefined.

一种可能性是fn参数,newUser无论它实际上是否为 a ,都将尝试调用它function

UserSchema.statics.newUser = function (email, password,username, fn) {
    //...
        fn(err, instance);
    //...
});

但是, 的值fn取决于您如何调用newUser

// fn = undefined
User.newUser('email@domain', 'password', 'username');

// fn = function
User.newUser('email@domain', 'pass', 'user', function (err, user) { });

因此,您要么想在尝试调用它之前测试它fnfunction

instance.save(function (err) {
    if (typeof fn === 'function') {
        fn(err, instance);
    }
});

或者您可以fn直接传递给Model#save,它已经处理了 when fnis undefined

instance.save(fn);
于 2012-10-30T04:04:03.313 回答