【发布时间】:2018-11-19 22:39:18
【问题描述】:
假设 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 的新手 - 有没有好的方法来实现它?
【问题讨论】:
-
您可以投影您的查询,也可以加密您的密码npmjs.com/package/bcrypt-nodejs