【问题标题】:How to verify if email exists in two seperate documents of mongoose?如何验证电子邮件是否存在于两个单独的猫鼬文档中?
【发布时间】:2019-12-11 18:02:23
【问题描述】:

我有两个模型,病人和医生。当用户登录时,无论是医生还是病人,只有一个路由运行后端的登录功能。但我不明白的是如何查询,以便使用单个查询在患者和医生的集合中进行搜索。

这是医生模型:

const doctorSchema = new Schema({
  firstName: {
    type: String,
    required: true
  },
  lastName: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  date: {
    type: Date,
    default: Date.now
  },
  practitionerLicense: {
    type: String,
    required: true
  }
});

module.exports = Doctor = mongoose.model("doctors", doctorSchema);

还有患者模型:

const patientSchema = new Schema({
  firstName: {
    type: String,
    required: true
  },
  lastName: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  date: {
    type: Date,
    default: Date.now
  }
});

module.exports = Patient = mongoose.model("patient", patientSchema);

现在我想要类似下面的伪代码,其中用户可以是基类或其他东西。

Users.findOne({email}).then(...)

我遇到了许多其他类似的问题,但看到了我认为不适合我的情况的填充方法。有什么建议吗?

【问题讨论】:

    标签: javascript mongoose


    【解决方案1】:

    除了practiceLicense 字段外,您的患者和医生架构几乎相同。

    因此,我将创建一个带有额外角色字段的通用用户架构,而不是两个不同的架构,如下所示:

    const userSchema = new Schema({
      firstName: {
        type: String,
        required: true
      },
      lastName: {
        type: String,
        required: true
      },
      email: {
        type: String,
        required: true
      },
      password: {
        type: String,
        required: true
      },
      date: {
        type: Date,
        default: Date.now
      },
      practitionerLicense: {
        type: String,
        required: false
      },
      role: {
        type: String,
        enum: ["patient", "doctor"],
        required: true
      }
    });
    
    module.exports = User = mongoose.model("users", userSchema);
    

    请注意,我还将从业者许可证的必需选项设置为 false。

    这样您就可以使用通用的用户登录表单和路由。

    如果您可以验证用户是否输入了从业者许可证,那么您在 React 中的注册路线和注册表单也可以是通用的,并且如果有这样的 API,您可以使用 API 对其进行验证。

    如果无法做到这一点,您的注册路线和注册组件对于患者和医生来说必须不同。当用户在患者登记表中注册时,您可以将角色设置为患者。并且当用户在医生注册表单中注册时,您可以将角色设置为医生。

    【讨论】:

    • 我明白你的意思,但如果我想要两个单独的模型而不是制作一个用户模型,那么我该如何解决这个问题。 mongoose 不是提供了某种方法在一个查询中遍历两个表吗?
    • @Emma 可能有另一种解决方案,仅使用第三个模式来处理电子邮件和密码。它适合你吗?但我仍然认为使用通用模式是这种场景的最佳解决方案。
    • 我还为患者和医生提供了单独的个人资料模型。例如,如果我使用您的方法,连接所有这些会不会很困难?
    • @Emma 如果配置文件数据也相似,您也可以使用通用配置文件模型。如果不可能,总是有猫鼬填充的解决方案。
    • 哦,好吧!如果现在我使用一个模型用户,那么还有一件事,那么如何在查询中编写枚举值。能否请您写一个示例查询,以便我了解。
    猜你喜欢
    • 2016-03-27
    • 2014-11-10
    • 1970-01-01
    • 2017-02-27
    • 2023-03-21
    • 2011-03-03
    • 2011-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多