Javascript 为什么我收到';对象不是函数';?
在我的nodejs应用程序中,在用户mongoose模式中,我有以下方法:Javascript 为什么我收到';对象不是函数';?,javascript,node.js,Javascript,Node.js,在我的nodejs应用程序中,在用户mongoose模式中,我有以下方法: /* * 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: {
/*
* 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();
你看到什么问题了吗?嗯。。。无法实例化mongoose.Schema。您需要从这样的模式创建一个模型
var UserModel = mongoose.model( 'UserModel', User );
要从架构中引用当前模型,可以执行
var newUser=newthis.constructor()
要创建新用户,您需要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)
});
});
};
我想。。。我们需要看到更多的代码。。。特别是在您创建
用户
的地方。错误表明用户
不是对函数的引用,而是对函数的引用variable@SarveshKumarSingh更新了我的问题。根据,您应该首先使用var UserModel=mongoose.model('User',User')将模式(User
)转换为模型代码>用户具有new Schema()的引用,这是一个对象。当您执行newuser()时,它将给出错误。