I have a simple node.js code that uses mongoose which works when saving but doesn\'t retrieve.
.save()
works, but .findOne()
doesn\'t.
To elaborate on the current answer which is correct, notice the difference between userSchema.path and userSchema.statics - the former uses 'this' as the instance of the model, while in the latter 'this' refers to the model "class" itself:
var userSchema = ...mongoose schema...;
var getUserModel = function () {
return mongoDB.model('users', userSchema);
};
userSchema.path('email').validate(function (value, cb) {
getUserModel().findOne({email: value}, function (err, user) {
if (err) {
cb(err);
}
else if(user){ //we found a user in the DB already, so this email has already been registered
cb(null,false);
}
else{
cb(null,true)
}
});
},'This email address is already taken!');
userSchema.statics.findByEmailAndPassword = function (email, password, cb) {
this.findOne({email: email}, function (err, user) {
if (err) {
return cb(err);
}
else if (!user) {
return cb();
}
else {
bcrypt.compare(password, user.passwordHash, function (err, res) {
return cb(err, res ? user : null);
});
}
});
};
};
findOne is a method on your Users
model, not your user
model instance. It provides its async results to the caller via callback:
Users.findOne({field:'value'}, function(err, doc) { ... });