【问题标题】:How to enforce uniqueness of 2 MongoDB fields in combination?如何强制组合 2 个 MongoDB 字段的唯一性?
【发布时间】:2015-01-11 03:29:23
【问题描述】:

我目前有一个 Comment MongoDB 表,我在其中强制 remote_id 字段的唯一性。

The MongoDB documentation is here.

我现在处于remote_id 属性应该只对拥有评论的用户唯一的情况。换句话说:

  • UserPeter只能有1个Commentremote_id123
  • UserJohn只能有1个Commentremote_id123
  • Users PeterJohn 都可以有 1 个 Commentremote_id 123

如何强制 2 个字段组合的唯一性?

我的表是在我的 Ruby on Rails 应用程序中的模型文件中定义的,它目前看起来像这样:

class Comment
  include Mongoid::Document
  include Mongoid::Timestamps

  field :datetime,          type: Time
  field :remote_id,         type: String

  index({ remote_id: 1 },   { unique: true })
  index({ user_id: 1 },     { background: true })

  belongs_to :user,         :inverse_of => :comments
end

【问题讨论】:

  • 我对Ruby一无所知,但您正在寻找的是一个独特的复合索引,它是在mongo shell中使用db.collection.ensureIndex({user_id:1,remote_id:1},{unique:true})创建的。
  • @MarkusWMahlberg Mongoid 的index 调用几乎直接转换为ensureIndex,所以index(x) 最终变成ensureIndex(x)。即使不了解 Ruby,您也非常接近答案。
  • 大家好。感谢您的参与。但是你们是说我的代码中当前为index({ remote_id: 1 }, { unique: true }) 的索引可能是index({ remote_id: 1, user_id: 1 }, { unique: true }) 吗?
  • 是的,应该可以。如果马库斯回答我会更舒服。
  • 我刚刚测试过,它确实有效。多谢你们。随意把它作​​为答案。

标签: ruby-on-rails mongodb mongoid


【解决方案1】:

您可以在模型中添加以下行

validates :remote_id, uniqueness: { scope: :user }

也为了完整性: 如果你想验证超过 2 个字段的唯一性

(例如,如果您希望 评论在每个用户的每个帖子中都是唯一的)使用以下

validates :remote_id, uniqueness: { scope: [:user, :post] }

假设评论有一个post 字段或关系。

【讨论】:

  • 嗨@artmees。我选择了index({ remote_id: 1, user_id: 1 }, { unique: true })
  • 我更喜欢使用验证,因为它看起来更好、更易读,并在表单中添加正确的错误,以防您使用RailsAdmin 之类的东西,但这是您的电话
猜你喜欢
  • 1970-01-01
  • 2014-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多