我可以使用以下方法将新文档保存到我的mongodb数据库。
User.prototype.save = function (fn) {
var user = new userModel({
user: this.user,
pass: this.pass
});
console.log('user: ' +user);
this.hashPassword (user.pass, function (err, salt, hash) {
if (err) return fn (err);
this.pass = hash;
user.salt = salt;
user.pass = hash;
user.save (function (err, product, numberAffected) {
if (err) return fn (err);
return fn(undefined);
});
});
};
现在我想在保存之前检查用户是否已经存在
User.prototype.save = function (fn) {
// See if the username exists
userModel.findOne ({ 'user': this.user }, function (err, user) {
if (err) return fn (err);
if (!user) {
user = new userModel({
user: this.user,
pass: this.pass
});
console.log('user: ' +user);
this.hashPassword (user.pass, function (err, salt, hash) {
if (err) return fn (err);
this.pass = hash;
user.salt = salt;
user.pass = hash;
user.save (function (err, product, numberAffected) {
if (err) return fn (err);
return fn(undefined);
});
});
} else {
// TODO: update all the user fields
console.log ('user already exists');
}
});
}
不再找到this.hashPassword TypeError: Object #<Promise> has no method 'hashPassword'
,现在用户的字段未定义。如何在这些回调中使用this
?
编辑1:
仔细观察我还注意到,第一个片段中的this.pass = hash;
对我关心的对象也没有任何作用。
答案 0 :(得分:1)
第2行
var self = this
然后,
self.hashPassword()
完整:
User.prototype.save = function (fn) {
var self = this;
// See if the username exists
userModel.findOne ({ 'user': self.user }, function (err, user) {
if (err) return fn (err);
if (!user) {
user = new userModel({
user: self.user,
pass: self.pass
});
console.log('user: ' +user);
self.hashPassword (user.pass, function (err, salt, hash) {
if (err) return fn (err);
self.pass = hash;
user.salt = salt;
user.pass = hash;
user.save (function (err, product, numberAffected) {
if (err) return fn (err);
return fn(undefined);
});
});
} else {
// TODO: update all the user fields
console.log ('user already exists');
}
});
}