我的申请被拆分为 多个微服务在 上运行的heroku dynos (他们不能访问彼此的文件)。有时,有多个微服务处理一个集合。因此,两个微服务都需要相应的 Mongoose 模式。
但是,并非两个微服务都需要完整的架构。例如,微服务 A 需要完整模式,而微服务 B 只需要该模式的几个字段。
微服务 A 中的示例架构:
var AccountSchema = mongoose.Schema({
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
phone: { type: String, required: true, unique: true },
forename: { type: String, required: true },
surname: { type: String, required: true },
middleInitals: { type: String, required: false },
failedLoginAttempts: { type: Number, required: true, default: 0 },
lockUntil: { type: Number },
createdAt: { type: Date, default: Date.now }
})
微服务 B 中的示例架构:
var AccountSchema = mongoose.Schema({
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
failedLoginAttempts: { type: Number, required: true, default: 0 },
lockUntil: { type: Number },
createdAt: { type: Date, default: Date.now }
})
我的方法
我会继续在每个微服务中创建一个新模式,仅包含所需的字段。但是不知道多个微服务向MongoDB数据库注册一个新的schema会不会有什么问题?例如,两个微服务都会尝试为
unique
创建索引。 field 。会不会有性能问题?有人有我可以使用的不同方法吗?这甚至是一种有效的方法吗?
提前致谢 :)
最佳答案
这是一个有效的方法。您可以有 2 个模式指向同一个集合。我已经测试过它并且它有效。
Mongoose is an Object Data Modeling (ODM) library ,并且您可以有 2 个对象查看同一个集合/(SQL 中的表或 View ) - 没问题。
没有理由出现性能问题,只要你有正确的索引。与对象数据建模无关。
您可能想要添加一些类型键,以便在获取请求时只能找到 type1/type2 帐户。在查找时,您可以通过投影限制获取正确的字段。
我认为索引中应该只有 2 个键 - 电子邮件 + 密码。如果您有电话索引和微服务 B:不要包含电话——您将在 unique index of phone 处违规。 .
但是如果你真的想要一个唯一的电话索引,你可以进行覆盖。您可以为 mircoservice B 生成电话的临时唯一值(使用自动生成或复制电子邮件值),您将在 mircoservice B 上忽略此值,并且仅在您拥有有效电话的微服务 A 中查找/更新/显示电话。当用户从 accountB 类型更改为 accountA 类型时 - 您必须确保用有效的电话号码替换错误的电话号码。
我认为同一个集合的 2 个模式没有问题——你只需要以正确的方式管理你的索引——以避免冲突,并确保你可以区分集合中的不同帐户类型。
关于node.js - 在多个微服务上使用 Mongoose 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61064270/