[英]Check if document already exists if not create one
Im learning expressjs + mongo. 我正在学习expressjs + mongo。 I want to check after user logs in with passport through Steam if his data is already in database if not to create a record for him.
我想在用户使用护照通过Steam登录后检查,如果他的数据已经在数据库中,如果不是为他创建记录。
For this I created a static method in schema. 为此我在schema中创建了一个静态方法。 Unfortunatelly i can't save from the inside of it.
不幸的是,我无法从内部拯救。
TypeError: Object # has no method 'create'
TypeError:Object#没有方法'create'
SteamAccountSchema.statics.checkAccount = function(identifier){
this.findOne({ 'identifier' : identifier }, function(err, account){
if(err) throw err;
console.log("Checking account:" + account)
if(account) {
console.log("user already in db")
return true
} else {
console.log("Creating new user account")
this.create({
name : 'username',
identifier: identifier
}, function(err){
if(err) throw err;
// if (err) return done(err);
return false
});
}
});
} }
Just cache the this object. 只需缓存此对象即可。 Ie in the code below self points to what you need:
即在下面的代码中, self指向您需要的内容:
SteamAccountSchema.statics.checkAccount = function(identifier){
var self = this;
this.findOne({ 'identifier' : identifier }, function(err, account){
if(err) throw err;
console.log("Checking account:" + account)
if(account) {
console.log("user already in db")
return true
} else {
console.log("Creating new user account")
self.create({
name : 'username',
identifier: identifier
}, function(err){
if(err) throw err;
// if (err) return done(err);
return false
});
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.