ChatGPT解决这个技术问题 Extra ChatGPT

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.

you can also do .populate('user': 1, 'password':0)

J
JohnnyHK

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

Great. Can you provide an example on who to add it in find? Assuming I have: Users.find({id: _id}) where should I add the "+password+?
Is there a way to apply this to the object passed to save() callback? Such that when I save a user profile the password isn't included in the callback parameter.
This is by far the best answer in my opinion. Add this once, and it is exclude. Much better than adding a select or exclude option to every query.
This should be the ultimate answer. Added to schema, and don't have to forget excluding during queries.
This is the most flexible solution!
a
aaronheckmann
.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.


this will also work .populate('user': 1, 'password':0)
I didn't understand why adding " - " works and was curious so found a decent explanation on the docs: When using string syntax, prefixing a path with - will flag that path as excluded. When a path does not have the - prefix, it is included. Lastly, if a path is prefixed with +, it forces inclusion of the path, which is useful for paths excluded at the schema level. Here's the link for the full thing mongoosejs.com/docs/api.html#query_Query-select
J
Joundill

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 }

I would go for the last option. Never select the password, except in the logIn / passwordUpdate functions you really need it in.
For some reason that option didn't work with Passport.js local strategy, don't know why.
Good answer, thanks!!! Don't know why but when I do .select("+field") it brings only the __id, even though .select("-field") excludes nicely the field I want
Sorry, it works perfect, didn't notice that select: false is mandatory
This is working for my local strategy: await User.findOne({ email: username }, { password: 1 }, async (err, user) => { ... });
I
Ikbel

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

I've tested every answer, I think this is the best option if you're developing an api.
This doesn't remove fields on population.
Best option for me, this approach doest not conflict with my authentication method
This is the best way to go if you're using an API. You never have to worry about forgetting to remove a field :)
Awesome, toJSON is probably what most people need instead of toObject. delete ret.password also works btw
Y
Ylli Gashi

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.


Can you not override the behavior in the login endpoint? If so, this seems like the safest option.
@erfling, it won't.
It will, you can use const query = model.findOne({ username }).select("+password"); and use that on login and password change/resetting routes and otherwise ensure it never comes out. This is by far way safer to have it not return by default as people are proven to mistakes imo
R
Ratan Uday Kumar

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

N
Nerius Jok

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.


R
Ricky Sahu

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


A
Anand Kapdi

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.


R
Rafał Bochniewicz

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; }, }, } );


Could you please explain why this solves the issue?
o
onkar

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


Great. Thanks. I like this approach.
p
prosoitos
router.get('/users',auth,(req,res)=>{
   User.findById(req.user.id)
    //skip password
    .select('-password')
    .then(user => {
        res.json(user)
    })
})

n
netishix

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;
  }
});

B
Bennett Adams

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);
    });
});

S
Sanket Berde

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

Regardless of password being hashed or not, the password/the hash should never shown to the user. An attacker can get some important information of the hashed password (which algorithm was used) and so.