Luis Elizondo
Luis Elizondo

Reputation: 2069

How to protect the password field in Mongoose/MongoDB so it won't return in a query when I populate collections?

Suppose I have two collections/schemas. One is the Users Schema with username and password fields, then, I have a Blogs Schema that has a reference to the Users Schema in the author field. If I use Mongoose to do something like

Blogs.findOne({...}).populate("user").exec()

I will have the Blog document and the user populated too, but how do I prevent Mongoose/MongoDB from returning the password field? The password field is hashed but it shouldn't be returned.

I know I can omit the password field and return the rest of the fields in a simple query, but how do I do that with populate. Also, is there any elegant way to do this?

Also, in some situations I do need to get the password field, like when the user wants to login or change the password.

Upvotes: 124

Views: 107746

Answers (16)

Parterdev
Parterdev

Reputation: 1211

*** I have two solutions for this:

// OPT: 1

/** If you print these params, the doc and ret are the same objects
 * and opt is another object with special params (only details): */

userSchema.set('toJSON', {
    transform: function(doc, ret, opt) {
        console.log("DOC-RET-OPT", {
            doc,
            ret,
            opt
        });
        // You can remove the specific params with this structure
        delete ret['password'];
        delete ret['__v'];
        return ret;
    }
});

// REMEMBER: You cannot apply destructuring for the objects doc or ret...

// OPT: 2

/* HERE: You can apply destructuring object 'cause the result
* is toObject instance and not document from Mongoose... */

userSchema.methods.toJSON = function() {
    const {
        __v,
        password,
        ...user
    } = this.toObject();
    return user;
};

// NOTE: The opt param has this structure:
opt: {
    _calledWithOptions: {},
    flattenDecimals: true,
    transform: [Function: transform],
    _isNested: true,
    json: true,
    minimize: true
}

Upvotes: 0

Eduardo Jasso
Eduardo Jasso

Reputation: 11

const { password,  ...others } = user._doc;

and send it like this

res.status(200).json(others);

Upvotes: 1

Luis Elizondo
Luis Elizondo

Reputation: 2069

Edit:

After trying both approaches, I found that the exclude always approach wasn't working for me for some reason using passport-local strategy, don't really know why.

So, this is what I ended up using:

Blogs.findOne({_id: id})
    .populate("user", "-password -someOtherField -AnotherField")
    .populate("comments.items.user")
    .exec(function(error, result) {
        if(error) handleError(error);
        callback(error, result);
    });

There's nothing wrong with the exclude always approach, it just didn't work with passport for some reason, my tests told me that in fact the password was being excluded / included when I wanted. The only problem with the include always approach is that I basically need to go through every call I do to the database and exclude the password which is a lot of work.


After a couple of great answers I found out there are two ways of doing this, the "always include and exclude sometimes" and the "always exclude and include sometimes"?

An example of both:

The include always but exclude sometimes example:

Users.find().select("-password")

or

Users.find().exclude("password")

The exclude always but include sometimes example:

Users.find().select("+password")

but you must define in the schema:

password: { type: String, select: false }

Upvotes: 40

Rafał Bochniewicz
Rafał Bochniewicz

Reputation: 211

const userSchema = new mongoose.Schema(
  {
    email: {
      type: String,
      required: true,
    },
    password: {
      type: String,
      required: true,
    },
  },
  {
    toJSON: {
      transform(doc, ret) {
        delete ret.password;
        delete ret.__v;
      },
    },
  }
);

Upvotes: 8

Gere
Gere

Reputation: 2184

I'm using for hiding password field in my REST JSON response

UserSchema.methods.toJSON = function() {
 var obj = this.toObject(); //or var obj = this;
 delete obj.password;
 return obj;
}

module.exports = mongoose.model('User', UserSchema);

Upvotes: 11

Nerius Jok
Nerius Jok

Reputation: 3227

I found another way of doing this, by adding some settings to schema configuration.

const userSchema = new Schema({
    name: {type: String, required: false, minlength: 5},
    email: {type: String, required: true, minlength: 5},
    phone: String,
    password: String,
    password_reset: String,
}, { toJSON: { 
              virtuals: true,
              transform: function (doc, ret) {
                delete ret._id;
                delete ret.password;
                delete ret.password_reset;
                return ret;
              }

            }, timestamps: true });

By adding transform function to toJSON object with field name to exclude. as In docs stated:

We may need to perform a transformation of the resulting object based on some criteria, say to remove some sensitive information or return a custom object. In this case we set the optional transform function.

Upvotes: 6

netishix
netishix

Reputation: 193

You can pass a DocumentToObjectOptions object to schema.toJSON() or schema.toObject().

See TypeScript definition from @types/mongoose

 /**
 * The return value of this method is used in calls to JSON.stringify(doc).
 * This method accepts the same options as Document#toObject. To apply the
 * options to every document of your schema by default, set your schemas
 * toJSON option to the same argument.
 */
toJSON(options?: DocumentToObjectOptions): any;

/**
 * Converts this document into a plain javascript object, ready for storage in MongoDB.
 * Buffers are converted to instances of mongodb.Binary for proper storage.
 */
toObject(options?: DocumentToObjectOptions): any;

DocumentToObjectOptions has a transform option that runs a custom function after converting the document to a javascript object. Here you can hide or modify properties to fill your needs.

So, let's say you are using schema.toObject() and you want to hide the password path from your User schema. You should configure a general transform function that will be executed after every toObject() call.

UserSchema.set('toObject', {
  transform: (doc, ret, opt) => {
   delete ret.password;
   return ret;
  }
});

Upvotes: 2

Cameron Hudson
Cameron Hudson

Reputation: 3929

The solution is to never store plaintext passwords. You should use a package like bcrypt or password-hash.

Example usage to hash the password:

 var passwordHash = require('password-hash');

    var hashedPassword = passwordHash.generate('password123');

    console.log(hashedPassword); // sha1$3I7HRwy7$cbfdac6008f9cab4083784cbd1874f76618d2a97

Example usage to verify the password:

var passwordHash = require('./lib/password-hash');

var hashedPassword = 'sha1$3I7HRwy7$cbfdac6008f9cab4083784cbd1874f76618d2a97';

console.log(passwordHash.verify('password123', hashedPassword)); // true
console.log(passwordHash.verify('Password0', hashedPassword)); // false

Upvotes: 1

Anand Kapdi
Anand Kapdi

Reputation: 501

While using password: { type: String, select: false } you should keep in mind that it will also exclude password when we need it for authentication. So be prepared to handle it however you want.

Upvotes: 5

Ikbel
Ikbel

Reputation: 7851

You can achieve that using the schema, for example:

const UserSchema = new Schema({/* */})

UserSchema.set('toJSON', {
    transform: function(doc, ret, opt) {
        delete ret['password']
        return ret
    }
})

const User = mongoose.model('User', UserSchema)
User.findOne() // This should return an object excluding the password field

Upvotes: 22

Ylli Gashi
Ylli Gashi

Reputation: 655

User.find().select('-password') is the right answer. You can not add select: false on the Schema since it will not work, if you want to login.

Upvotes: 14

Ricky Sahu
Ricky Sahu

Reputation: 24309

Blogs.findOne({ _id: id }, { "password": 0 }).populate("user").exec()

Upvotes: 4

Bennett Adams
Bennett Adams

Reputation: 1818

This is more a corollary to the original question, but this was the question I came across trying to solve my problem...

Namely, how to send the user back to the client in the user.save() callback without the password field.

Use case: application user updates their profile information/settings from the client (password, contact info, whatevs). You want to send the updated user information back to the client in the response, once it has successfully saved to mongoDB.

User.findById(userId, function (err, user) {
    // err handling

    user.propToUpdate = updateValue;

    user.save(function(err) {
         // err handling

         /**
          * convert the user document to a JavaScript object with the 
          * mongoose Document's toObject() method,
          * then create a new object without the password property...
          * easiest way is lodash's _.omit function if you're using lodash 
          */

         var sanitizedUser = _.omit(user.toObject(), 'password');
         return res.status(201).send(sanitizedUser);
    });
});

Upvotes: 3

JohnnyHK
JohnnyHK

Reputation: 311865

You can change the default behavior at the schema definition level using the select attribute of the field:

password: { type: String, select: false }

Then you can pull it in as needed in find and populate calls via field selection as '+password'. For example:

Users.findOne({_id: id}).select('+password').exec(...);

Upvotes: 395

Adam Comerford
Adam Comerford

Reputation: 21682

Assuming your password field is "password" you can just do:

.exclude('password')

There is a more extensive example here

That is focused on comments, but it's the same principle in play.

This is the same as using a projection in the query in MongoDB and passing {"password" : 0} in the projection field. See here

Upvotes: 3

aaronheckmann
aaronheckmann

Reputation: 10780

.populate('user' , '-password')

http://mongoosejs.com/docs/populate.html

JohnnyHKs answer using Schema options is probably the way to go here.

Also note that query.exclude() only exists in the 2.x branch.

Upvotes: 78

Related Questions