未找到鉴别器键时的 Mongoid 行为
Posted
技术标签:
【中文标题】未找到鉴别器键时的 Mongoid 行为【英文标题】:Mongoid behavior when discriminator key is not found 【发布时间】:2021-10-29 14:52:10 【问题描述】:看着mongoid inheritance documentation 它说:
类似地,当通过父类(本例中为 Canvas)进行查询时,集合中没有鉴别器值或鉴别器值未映射到父类或其任何后代的任何文档都将被返回作为父类的实例。
使用该页面上的示例类:
class Canvas
include Mongoid::Document
field :name, type: String
embeds_many :shapes
end
class Browser < Canvas
field :version, type: Integer
scope :recent, -> where(:version.gt => 3)
end
如果我像这样将文档插入 Canvas 集合:
"_id": "$oid": "612d5bd10170cb02ad9bfbac" ,
"_type":"SpecialCanvas"
然后像这样查询该文档:
Canvas.find_by(id: '612d5bd10170cb02ad9bfbac')
我收到此错误:
Mongoid::Errors::UnknownModel:
message:
Attempted to instantiate an object of the unknown Model 'SpecialCanvas'.
summary:
A document with the value 'SpecialCanvas' at the key '_type' was used to instantiate a model object but Mongoid cannot find this Class.
resolution:
The _type field is a reserved one used by Mongoid to determine the class for instantiating an object. Please don't save data in this field or ensure that any values in this field correspond to valid Models.
from /usr/local/bundle/gems/mongoid-7.2.5/lib/mongoid/factory.rb:87:in `rescue in from_db'
Caused by NameError: uninitialized constant SpecialCanvas
from /usr/local/bundle/gems/activesupport-5.2.6/lib/active_support/inflector/methods.rb:283:in `block in constantize'
但是,根据文档,我希望它只返回父类 (Canvas) 的一个实例。我是不是误会了?
【问题讨论】:
【参考方案1】:对我来说似乎是一个文档错误。请向https://jira.mongodb.org/browse/MONGOID举报。
【讨论】:
以上是关于未找到鉴别器键时的 Mongoid 行为的主要内容,如果未能解决你的问题,请参考以下文章
在 URL 包含“#”的地址栏中按下 Enter 键时的行为