Quick code:
var userSchema = new mongoose.Schema({
username: String,
password: {type: String, select: false}
});
userSchema.methods.checkPassword = function(password, done) {
console.log(password); // Password to check
console.log(this.password); // stored password
...
};
I don't want the password to be accessible by default, but I need a method to check against a user inputted password before authenticating the user. I know I can do a query to the DB to include these values, but I'm a bit lost on how I could access the hidden property on the schema method itself. this
in the method itself is just the returned query, so it seems like it is inaccessible? Should I be doing the checkPassword()
function elsewhere?
select: false makes field values not accessible using "this. field_name" · Issue #1596 · Automattic/mongoose · GitHub.
A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.
The $set operator replaces the value of a field with the specified value. The $set operator expression has the following form: { $set: { <field1>: <value1>, ... } } To specify a <field> in an embedded document or in an array, use dot notation.
The __v field is called the version key. It describes the internal revision of a document. This __v field is used to track the revisions of a document. By default, its value is zero ( __v:0 ).
You can explicitly allow the password field (with {select:"false"}) to be returned in your find call with "+" operator before field e.g.:
User.findOne({}).select("+password") // "+" = allow select hidden field
You can use select
to select password in query. This is an example query.
User.findOne().select('password').exec(callback);
And this must be what you want to check password.
userSchema.methods.checkPassword = function(password, done) {
User.findOne({username: this.username}).select('password').exec(function (err, user) {
if (user.password == password)
return true;
else
return false;
});
}
I hope this might help you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With