在我的nodejs app中,在User mongoose schema中我有这个方法:
/*
* 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();
你看到有什么问题吗?
答案 0 :(得分:1)
嗯...... mongoose.Schema无法实例化。您需要从这样的模式中创建模型,
var UserModel = mongoose.model( 'UserModel', User );
答案 1 :(得分:1)
要从架构中引用当前模型,您可以执行var newUser = new this.constructor();
答案 2 :(得分: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)
});
});
};