首页 > 解决方案 > 如何在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: falseon passwordfield 选项,它有效,但是当我无法登录我的应用程序时。一定有别的办法。

标签: mongodbexpress

解决方案


简单而可取的方式:

您可以使用字段的 select 属性在架构定义级别更改默认行为:

password: { type: String, select: false }

然后,您可以根据需要在查找中将其拉入,并通过字段选择将调用填充为“+密码”。例如:

Users.findOne({_id: id}).select('+password').exec(...);

推荐阅读