如何在Mongoid中强制执行唯一的嵌入式文档 [英] How to enforce unique embedded document in mongoid

查看:74
本文介绍了如何在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中强制执行唯一的嵌入式文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆