如何在Mongoid中强制执行唯一的嵌入式文档

编程入门 行业动态 更新时间:2024-10-20 05:29:52
本文介绍了如何在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中强制执行唯一的嵌入式文档

本文发布于:2023-10-14 22:12:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1492365.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌入式   强制执行   文档   如何在   Mongoid

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!