mongodb - 固定值字段的 Mongoose 复合索引

标签 mongodb mongoose

是否可以创建一个复合索引,其中一个字段具有固定值?

假设我想避免用户对不​​同的帐户使用相同的电子邮件,而只是对常规用户帐户使用相同的电子邮件,并且我希望允许管理员在任意多的地方使用邮件,甚至可以有一个常规的电子邮件地址。使用同一电子邮件的用户帐户和管理帐户

User.index({ username: 1, email: 1 }, { unique: true })

没有用,因为它不允许管理员重复使用电子邮件。是否可以做类似的事情?

User.index({ role: "regular_user", username 1, email: 1}, { unique: true });

最佳答案

路易斯,

关于你给出的例子。如果创建唯一复合索引,各个键可以具有相同的值,但索引条目中存在的键之间的值组合只能出现一次。因此,如果我们在 {"username": 1, "role": 1} 上有一个唯一索引。以下插入是合法的:

> db.users.insert({"username" : "Luis Sieira"})
> db.users.insert({"username" : "Luis Sieira", "role" : "regular"})
> db.users.insert({"username" : "Luis Sieira", "role" : "admin"})

如果您尝试插入上述任何文档的第二个副本,则会导致重复键异常。

您的场景

我认为如果您在架构中添加了一个 allowance 字段。当您为新帐户的管理员插入时。您可以为其管理津贴添加不同的值。如果您为 {"username":1,"email":1, "allowance": 1}

添加了唯一索引

您可以合法地进行以下插入:

>db.users.insert({"username" : "inspired","email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a0c9e0d3cf8ec3cfcd" rel="noreferrer noopener nofollow">[email protected]</a>", "allowance": 0})
>db.users.insert({"username" : "inspired","email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5c351c2f33723f3331" rel="noreferrer noopener nofollow">[email protected]</a>", "allowance": 1})
>db.users.insert({"username" : "inspired","email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="046d44776b2a676b69" rel="noreferrer noopener nofollow">[email protected]</a>", "allowance": 2})
>db.users.insert({"username" : "inspired","email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ee7cefde1a0ede1e3" rel="noreferrer noopener nofollow">[email protected]</a>", "allowance": 3})

当然,您必须处理来自客户端的某些逻辑,但这将允许您对常规帐户使用限额代码0,然后允许每次管理员创建另一个帐户时,您都可以保存更高的津贴代码(增加它或为其添加自定义值)。

我希望这能为使用独特的复合索引提供一些指导。

关于mongodb - 固定值字段的 Mongoose 复合索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33569340/

相关文章:

mongodb - 从近查询中检索距离 "dis"结果

mongodb - 在 Ubuntu 16.04 上安装 MongoDB

mongodb - 发布数据时出现超时错误

MongoDB - 按客户分组并检索最高价格的文档

node.js - 在 Mongodb 中使用自定义 ID 的效率成本是多少

node.js - $elemMatch 返回误报

java - 条件存储库注入(inject) - Spring Boot

node.js - 如何设置打字鹅

node.js - 如何从 Mongodb 数据库中减去 ISOFormat [2018-08-11T12 :23:55. 627Z] 的时间?

node.js - 无法从 session Express 获取用户 ID