如何在 Mongoose/MongoDB 中保护密码字段,使其在填充集合时不会在查询中返回?

假设我有两个集合/模式。一个是具有用户名和密码字段的 Users Schema,然后,我有一个 Blog Schema,它在 author 字段中引用了 Users Schema。如果我用猫鼬

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

我将有 Blog 文档和用户填充,但是如何防止 Mongoose/MongoDB 返回密码字段?Password 字段是散列的,但不应该返回。

我知道我可以省略 password 字段,并在一个简单的查询中返回其余字段,但是我如何使用填充。还有,有什么优雅的方法吗?

此外,在某些情况下,我确实需要获得密码字段,如当用户想要登录或更改密码。

84907 次浏览

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

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

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

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

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.

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

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

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.

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

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

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.

router.get('/users',auth,(req,res)=>{
User.findById(req.user.id)
//skip password
.select('-password')
.then(user => {
res.json(user)
})
})

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

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

and send it like this

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

*** 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
}