【问题标题】:mongoose schema contains entire DB object instead of defined schema object猫鼬模式包含整个数据库对象而不是定义的模式对象
【发布时间】:2020-03-18 17:31:54
【问题描述】:

我正在为用户使用两种模式。一个包含密码/盐,一个不包含返回前端。当我使用使用没有密码的模式的模型时,它仍然返回密码:/

通用用户(用于发送给客户端)

module.exports = {    
    username: String,
    email: String,
    firstName: String,
    lastName: String,
    createdOn: Date,
    updatedOn: Date,
    scopes: [String]
}

Auth User(用于创建/更新/验证用户)

module.exports = {    
    username: String,
    email: String,
    password: String,
    salt: String,
    firstName: String,
    lastName: String,
    createdOn: Date,
    updatedOn: Date,
    scopes: [String]
}

创建模型

var modelInstance = mongoose.model("authUser", authUserSchema, 'users')

(在不同的文件中)

var modelInstance = mongoose.model("user", userSchema, 'users')

modelInstance 被导出 module.exports = modelInstance;

更新这个问题回答了我的问题。 How to protect the password field in Mongoose/MongoDB so it won't return in a query when I populate collections?

【问题讨论】:

  • 这两个你都坚持吗?即每个用户有两个条目?
  • 好吧,两个模型都代表同一个集合users,无论您从哪个模型执行查询,它都会返回字段。要限制字段there are various ways,防止在从userSchema 的模型中查询时选择password 字段。还假设您在节点中遵循 每个文件一个模式/模型 结构
  • @ambianBeing 该链接正是我所需要的。我之前只是没有在寻找正确的东西 :( 但是最好有像这样的问题的变化 b/c 不是每个人都会以同样的方式解决问题。

标签: node.js mongoose


【解决方案1】:

您没有明确的问题,但我想您是在问是否可以限制它。默认情况下,答案是“否”。

有一个插件:https://www.npmjs.com/package/mongoose-strictmodel 但它确实已经过时了。

虽然创建包装函数很容易:

function safeUser(userModel) {
  return {
    username: userModel.username,
    email: userModel.email,
    firstName: userModel.firstName,
    lastName: userModel.lastName,
    createdOn: userModel.createdOn,
    updatedOn: userModel.updatedOn,
    scopes: userModel.scopes
  }
}

【讨论】:

    猜你喜欢
    • 2019-02-20
    • 2016-09-02
    • 2019-10-30
    • 2019-03-21
    • 2021-04-10
    • 1970-01-01
    • 2020-03-10
    • 2017-01-28
    • 1970-01-01
    相关资源
    最近更新 更多