如何在 mongodb 响应中排除密码字段?

hel*_*999 1 mongodb express

每当向后端发出获取用户的请求时,我都会使用散列密码返回该用户。

        {
            "_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
        }
Run Code Online (Sandbox Code Playgroud)

用户模型

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 })
Run Code Online (Sandbox Code Playgroud)

列出用户路由

    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 })
            }
        })
    }
Run Code Online (Sandbox Code Playgroud)

虽然我已经在用户模式中声明了密码字段,但有什么方法可以在没有密码字段的情况下取回响应对象吗?selected: false我尝试了用户模型中的on字段选项password,它有效,但是当我无法登录我的应用程序时。一定还有其他办法。

lok*_*ngh 8

简单且优选的方式:

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

password: { type: String, select: false }
Run Code Online (Sandbox Code Playgroud)

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

Users.findOne({_id: id}).select('+password').exec(...);
Run Code Online (Sandbox Code Playgroud)


Abd*_*bid 5

您可以在进行查询调用时删除该字段,例如下面的代码根据 id 查找用户并删除密码字段。用户是用户架构,希望这有帮助

let user = await User.findById(id).select("-password");
Run Code Online (Sandbox Code Playgroud)