首页 > 解决方案 > 如何将 MogoDB 对象“解析”为 Nodejs 中的特定 JSON 结构?

问题描述

假设 MongoDB 中有以下用户模式(使用 Mongoose/Nodejs):

var UserSchema = new Schema({
    email: {
        type: String,
        unique: true,
        required: 'User email is required.'
    },
    password: {
        type: String,
        required: 'User password is required.'
    },
    token: {
        type: String,
        unique: true,
        default: hat
    },
    created_at: {
        type: Date,
        default: Date.now
    },
});

// mongoose-encrypt package
UserSchema.plugin(encrypt, {
    secret: 'my secret',
    encryptedFields: ['email', 'password', 'token', 'created_at']
});

现在假设我想从 API 端点返回用户对象。事实上,假设我想从多个 API 端点返回用户对象。可能作为独立对象,也可能作为相关模型。

显然,我不想password出现在返回的结构中——而且在很多情况下我也不想token被返回。我可以在每个端点上手动执行此操作,但我更喜欢无需考虑的解决方案 - 能够简单地检索用户,故事结束,而不用担心事后取消设置某些值。

我主要来自 Laravel 的世界,那里存在诸如 API 资源(https://laravel.com/docs/5.6/eloquent-resources)之类的东西。我已经尝试实现mongoose-hidden包(https://www.npmjs.com/package/mongoose-hidden)来隐藏密码和令牌,但不幸的是,这似乎破坏了我正在使用的加密包。

一般来说,我是 Nodejs 和 MongoDB 的新手——有没有好的方法来实现这个?

标签: node.jsmongodbmongoose

解决方案


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

您可以使用这个:Users.find().select("-password"),但是每当您将查询的项目发送给用户时都会这样做(res.json()...),因此您可以使用它进行操作包含字段,然后在将其发回之前将其从用户中删除(这是使用承诺方法,最佳实践)。如果您希望将您的更改用作默认设置,您可以将“select: false”添加到架构对象的密码字段中。

希望这可以帮助 :)


推荐阅读