mongodb - 如何在mongodb的响应中排除密码字段?
问题描述
每当向后端发出获取用户的请求时,我都会使用散列密码找回该用户。
{
"_id": "5e4e3e7eecd9a53c185117d4",
"username": "rick",
"email": "rick@gmail.com",
"password": "$2b$10$/eD8g4jCw6Bx0.FNxFDADO5tc70AvUmK0H/7R/0JTyo2q9PcGAdOO",
"createdAt": "2020-02-20T08:08:30.878Z",
"updatedAt": "2020-02-20T08:08:30.878Z",
"__v": 0
}
用户模型
const userSchema = new Schema({
username: { type: String, required: true },
email: { type: String, required: true },
password: { type: String, required: true },
posts: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Post"
}]
}, { timestamps: true })
列表用户路线
listUsers: (req, res) => {
User.find{}, (err, users) => {
if (err) {
return res.status(500).json({ error: "Server error occurred" })
} else if (!users) {
return res.status(400).json({ error: "No users found" })
} else if (users) {
return res.status(200).json({ users: users })
}
})
}
虽然我已经在用户模式中声明了密码字段,但有没有办法在没有密码字段的情况下取回响应对象?我尝试了用户模型中的selected: false
on password
field 选项,它有效,但是当我无法登录我的应用程序时。一定有别的办法。
解决方案
简单而可取的方式:
您可以使用字段的 select 属性在架构定义级别更改默认行为:
password: { type: String, select: false }
然后,您可以根据需要在查找中将其拉入,并通过字段选择将调用填充为“+密码”。例如:
Users.findOne({_id: id}).select('+password').exec(...);
推荐阅读
- mysql - 将查询结果保存到变量 Alexa Skills Json
- android - 带有导航组件问题的导航抽屉
- python - 在一个单列 SQLITE 中插入多个值
- python - 在python中将多个numpy数组(图像)组合到一个数组(图像)中
- java - Java - 在 2 个级别使用 2 个小数位舍入 BigDecimal 值
- sql - 根据 SQL 中的条件获取特定记录
- c# - 如何在 c# 图表中显示 Weekly BirthDate 的计数?
- haskell - 如果导入外部包,GHCi 无法加载导入“Data.Set”或“Data.Maybe”的脚本
- zsh - Zsh/Users/*******/.zshrc:13:不匹配
- oracle - 19c 的性能问题