2015-02-24 55 views
0

在我的NodeJS应用程序,用户猫鼬架构里面我有这样的方法:为什么我收到'对象不是函数'?

/* 
* Passport-Local Mongoose will add a username, hash and salt field to store the username, the hashed password and the salt value. 
*/ 
var User = new Schema({ 
    email: String, 
    token: String, 
    twitter: { 
    id: String, 
    token: String, 
    displayName: String, 
    } 
}); 

    /* 
* Find user by twitter id. 
*/ 
User.statics.findOrCreateByTwitterId = function (token, tokenSecret, profile, fn) { 
    this.findOne({ 
    'twitter.id': profile.id 
    }, function (err, user) { 
    if (err) return fn(err, null); 
    if (user) { 
     return fn(null, user) 
    }; 

    // create user 
    var newUser = new User(); 
    newUser.username = profile.username; 
    newUser.twitter.id = profile.id; 
    newUser.token = token; 
    newUser.displayName = profile.displayName; 

    // create user 
    newUser.save(function (err) { 
     if (err) { 
     return fn(null, null); 
     } 
     return fn(null, newUser) 

    }); 

    }); 
}; 

User.plugin(passportLocalMongoose); 

module.exports = mongoose.model('User', User); 

当它被称为我收到:

2015-02-24T07:47:24.162Z - debug: Mongoose: - users - findOne - { 'twitter.id': '90411931' } 
2015-02-24T07:47:24.327Z - error: Caught exception: TypeError: object is not a function 

,其中第32行是:

var newUser = new User(); 

待办事项你看到任何问题?

+1

我想......我们需要看到更多的代码.. 。特别是你创建你的用户的地方。 – 2015-02-24 07:51:57

+0

错误提示'用户'不是对函数的引用,而是对变量的引用 – 2015-02-24 07:52:20

+0

@SarveshKumarSingh更新了我的问题。 – 2015-02-24 07:53:16

回答

1

呃... mongoose.Schema无法实例化。你需要从这样的模式创建一个模型,

var UserModel = mongoose.model('UserModel', User); 
1

要从架构中引用当前模型,你可以做var newUser = new this.constructor();

0

要创建一个新用户,则需要new模型,而不是User模式。所以节省掉初始this在静态函数是这样的模型,因此它不是findOne回调赔了进去一次,然后用它来创建用户:

User.statics.findOrCreateByTwitterId = function (token, tokenSecret, profile, fn) { 
    var model = this; 
    model.findOne({ 
    'twitter.id': profile.id 
    }, function (err, user) { 
    if (err) return fn(err, null); 
    if (user) { 
     return fn(null, user) 
    }; 

    // create user 
    var newUser = new model(); 
    newUser.username = profile.username; 
    newUser.twitter.id = profile.id; 
    newUser.token = token; 
    newUser.displayName = profile.displayName; 

    // create user 
    newUser.save(function (err) { 
     if (err) { 
     return fn(null, null); 
     } 
     return fn(null, newUser) 

    }); 

    }); 
}; 
相关问题