假设我用几个索引定义了我的模型 Person:
class Person
include Mongoid::Document
field :email
field :ssn
index({ email: 1 }, { unique: true })
index({ ssn: 1 }, { unique: true })
end
但是,只有电子邮件索引已经存在于数据库中,所以当我调用
Person.collection.indexes.each {|i| puts i.inspect}
我得到以下响应:
{"v"=>1, "key"=>{"_id"=>1}, "name"=>"_id_", "ns"=>"x.person"}
{"v"=>1, "unique"=>true, "key"=>{"email"=>1}, "name"=>"email_1", "ns"=>"x.person"}
问题是,我怎样才能获得模型中已定义索引的列表,即使它们尚未在 mongo 中创建?
在我的例子中,这样的列表应该包括字段“ssn”的定义
也就是说...如何获取那些还没有创建的索引?
最佳答案
Person.index_specifications
显示模型中定义的索引,无论它是否存在于数据库中。
和
Person.collection.indexes
只显示数据库中实际存在的索引。
所以还有一点值得关注:
rake db:mongoid:create_indexes
将在数据库中创建模型中定义的索引,它实际上使用了方法'index_specifications'。
虽然这会删除除主键索引之外的所有索引:
rake db:mongoid:remove_indexes
所以当你只想删除数据库中存在但不再定义在数据库中的索引时,你应该使用这个:
rake db:mongoid:remove_undefined_indexes
在契约中使用方法“undefined_indexes”。
希望对您有所帮助。
文档在这里:
https://mongoid.github.io/en/mongoid/docs/indexing.html
http://www.rubydoc.info/github/mongoid/mongoid/Mongoid/Tasks/Database#create_indexes-instance_method
关于ruby - 如何为模型获取新的 mongoid 索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35613197/