【问题标题】:mongoid unique index allowed duplicate valuesmongoid 唯一索引允许重复值
【发布时间】:2012-11-26 18:45:40
【问题描述】:

我有一个以用户名作为字段的集合。模型将此字段定义为唯一的。但是我能够在数据库中插入一个重复的值。

class Profile
  include Mongoid::Document
  include Mongoid::Paperclip

  field :username
  index({ username: 1 } , { unique: true })
end

但该集合有 2 个相同的用户名

{ "_id" : ObjectId( "50b3b323421aa95da6000004" ),
  "username" : "marceloreuse" }

{ "_id" : ObjectId( "50b3b567421aa93d84000002" ),
  "username" : "marceloreuse" }

这里出了什么问题?

【问题讨论】:

  • 您的示例还显示了完全相同的 ObjectId - 这是正确的还是复制/粘贴疏忽?
  • 我的错...这是一个复制粘贴问题
  • 出于好奇 - 这不是分片集合,是吗?
  • 不,它是一个正常的集合

标签: ruby-on-rails-3 mongodb mongoid


【解决方案1】:

我会仔细检查您的索引 - 从控制台尝试 db.collection.getIndexes() 并确保您的索引存在。

如果您错过了它,Mongoid 不会自动构建索引,因为您指定了它 - 您需要运行包含的:rake db:mongoid:create_indexes

【讨论】:

  • 但是,mongoid 在添加重复条目时仍然没有抛出错误。该条目未添加,但 mongoid 没有给出任何错误。
  • 这是由于 MongoDB 中的默认 write concern - 驱动程序不会等待响应 - 这意味着您需要调用 getLastError 或更改持久性设置 persist_in_safe_mode。查看Mongoid: Persistence - Safe Mode
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-12
  • 2021-04-24
  • 2018-06-15
相关资源
最近更新 更多