mongoid唯一索引允许重复值

Ami*_*mit 5 mongodb mongoid ruby-on-rails-3

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

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

  field :username
  index({ username: 1 } , { unique: true })
end
Run Code Online (Sandbox Code Playgroud)

但是Collection有两个相同的用户名

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

{ "_id" : ObjectId( "50b3b567421aa93d84000002" ),
  "username" : "marceloreuse" }
Run Code Online (Sandbox Code Playgroud)

这里出了什么问题?

kmf*_*mfk 10

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

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