Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose: How can I access a select:false property in a schema method?

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?

like image 588
enrique-ramirez Avatar asked Mar 03 '15 17:03

enrique-ramirez


People also ask

What is select false in Mongoose schema?

select: false makes field values not accessible using "this. field_name" · Issue #1596 · Automattic/mongoose · GitHub.

What can Mongoose specify in a schema?

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.

What does $Set do in Mongoose?

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.

What is __ V in MongoDB?

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 ).


2 Answers

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
like image 195
Denys Pugachov Avatar answered Sep 22 '22 08:09

Denys Pugachov


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.

like image 21
Khay Avatar answered Sep 20 '22 08:09

Khay