【问题标题】:Mongoose - Protect the password field depending on the requested routeMongoose - 根据请求的路线保护密码字段
【发布时间】:2021-12-31 22:46:53
【问题描述】:

给定以下用户模型:

const UserSchema = new mongoose.Schema({
  id: Number,
  userID: {
    type: String,
    unique: true
  },
  userName: String,
  password: {type: String, select: false}, 
  isAdministrator: {
    type: Boolean,
    default: false
  }
}, {
  timestamps: true
});

此模型可确保在请求时不返回密码。

如何更改 UserModel 以便返回 Route A 而不是 Route B 的密码?

例如:

router.get('/A', [returns password])
router.get('/B', [returns no password])

【问题讨论】:

    标签: javascript express mongoose mongoose-schema


    【解决方案1】:

    在您执行 Mongoose 查询的控制器中, 例如:

    User.findOne({email})
    

    你附加一个选择函数并在括号内放入你想要被选择的字段,例如:

    User.findOne({email}).select("+password")
    

    如果您输入“-”,它将排除该字段,如果您不输入任何符号,它将选择该字段,“+”强制选择在架构。

    Query.prototype.select() documentation

    【讨论】:

      猜你喜欢
      • 2013-12-20
      • 2015-01-26
      • 2011-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-12
      • 2019-02-14
      • 1970-01-01
      相关资源
      最近更新 更多