node.js - 如何将 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 的新手——有没有好的方法来实现这个?
解决方案
如何保护 Mongoose/MongoDB 中的密码字段,以便在填充集合时它不会在查询中返回?
您可以使用这个:Users.find().select("-password"),但是每当您将查询的项目发送给用户时都会这样做(res.json()...),因此您可以使用它进行操作包含字段,然后在将其发回之前将其从用户中删除(这是使用承诺方法,最佳实践)。如果您希望将您的更改用作默认设置,您可以将“select: false”添加到架构对象的密码字段中。
希望这可以帮助 :)
推荐阅读
- bison - Flex 和 Bison 无法识别字符
- c# - 如何在 ASP.NET Core 中创建可更改的来自电子邮件的联系表单
- android - 我应该为改造请求设置什么超时?
- javascript - 如何从另一个组件打开对话框?
- c# - 如何使用 autofac 解析组件 Asp.net Web Api
- visual-studio-code - VScode(突然)不会打开文件夹
- php - 如何在 WooCommerce 中将鼠标悬停在产品上添加更多信息(摘录)
- node.js - Sequelize退货日期早于收到
- graphql - 苦艾酒数据加载器:Absinthe.Resolution.Helpers.dataloader/2 中的匿名 fn/3 中没有函数子句匹配
- c - 如何在 Cygwin 上安装 GCC