如何保护 Mongoose/MongoDB 中的密码字段,使其在填充集合时不会在查询中返回? [英] How to protect the password field in Mongoose/MongoDB so it won't return in a query when I populate collections?

查看:25
本文介绍了如何保护 Mongoose/MongoDB 中的密码字段,使其在填充集合时不会在查询中返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个集合/模式.一个是带有用户名和密码字段的用户架构,然后,我有一个博客架构,它在作者字段中引用了用户架构.如果我使用猫鼬做类似的事情

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

我将同时填充博客文档和用户,但如何防止 Mongoose/MongoDB 返回密码字段?密码字段已散列,但不应返回.

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.

我知道我可以省略密码字段并在一个简单的查询中返回其余的字段,但是我如何使用 populate 来做到这一点.另外,有没有什么优雅的方法可以做到这一点?

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.

推荐答案

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

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

JohnnyHK 的回答使用 Schema 选项可能是这里的方法.

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

还要注意 query.exclude() 只存在于 2.x 分支中.

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

这篇关于如何保护 Mongoose/MongoDB 中的密码字段,使其在填充集合时不会在查询中返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆