本文介绍了如何在Mongoid中强制执行唯一的嵌入式文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下型号
class Person include Mongoid::Document embeds_many :tasks end class Task include Mongoid::Document embedded_in :commit, :inverse_of => :tasks field :name end如何确保以下内容?
person.tasks.create :name => "create facebook killer" person.tasks.create :name => "create facebook killer" person.tasks.count == 1 different_person.tasks.create :name => "create facebook killer" person.tasks.count == 1 different_person.tasks.count == 1即任务名称在特定人员中是唯一的
i.e. task names are unique within a particular person
检查了有关索引的文档后,我认为以下方法可能会起作用:
Having checked out the docs on indexes I thought the following might work:
class Person include Mongoid::Document embeds_many :tasks index [ ["tasks.name", Mongo::ASCENDING], ["_id", Mongo::ASCENDING] ], :unique => true end但是
person.tasks.create :name => "create facebook killer" person.tasks.create :name => "create facebook killer"仍然会产生重复.
上面Person中显示的索引配置将转换为mongodb
The index config shown above in Person would translate into for mongodb
db.things.ensureIndex({firstname : 1, 'tasks.name' : 1}, {unique : true})推荐答案
默认情况下,索引不是唯一的.如果您查看 Mongo Docs ,那么唯一性就是一个额外的标志
Indexes are not unique by default. If you look at the Mongo Docs on this, uniqueness is an extra flag.
我不知道确切的Mongoid翻译,但是您正在寻找这样的东西:
I don't know the exact Mongoid translation, but you're looking for something like this:
db.things.ensureIndex({firstname : 1}, {unique : true, dropDups : true})
更多推荐
如何在Mongoid中强制执行唯一的嵌入式文档
发布评论