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 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(...);
.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.
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 }
.select("+field")
it brings only the __id
, even though .select("-field")
excludes nicely the field I want
select: false
is mandatory
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
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.
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
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);
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.
Blogs.findOne({ _id: id }, { "password": 0 }).populate("user").exec()
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.
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; }, }, } );
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
router.get('/users',auth,(req,res)=>{
User.findById(req.user.id)
//skip password
.select('-password')
.then(user => {
res.json(user)
})
})
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;
}
});
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);
});
});
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
Success story sharing