【问题标题】:How can you update/destroy one embed document that is inside of all documents on a collection如何更新/销毁集合中所有文档中的一个嵌入文档
【发布时间】:2013-02-16 18:39:23
【问题描述】:

我的应用程序模型允许患者拥有自定义字段。所有患者都有相同的海关领域。海关字段嵌入在患者文档中。我应该能够添加、更新和删除自定义字段,并且此类操作扩展到所有患者。

class Patient
  include Mongoid::Document
  embeds_many :custom_fields, as: :customizable_field

  def self.add_custom_field_to_all_patients(custom_field)
    Patient.all.add_to_set(:custom_fields, custom_field.as_document)
  end

  def self.update_custom_field_on_all_patients(custom_field)       
    Patient.all.each { |patient| patient.update_custom_field(custom_field) }
  end

  def update_custom_field(custom_field)
    self.custom_fields.find(custom_field).update_attributes({ name: custom_field.name, show_on_table: custom_field.show_on_table } )
  end

  def self.destroy_custom_field_on_all_patients(custom_field)
    Patient.all.each { |patient| patient.remove_custom_field(custom_field) }
  end    

  def remove_custom_field(custom_field)
    self.custom_fields.find(custom_field).destroy
  end
end

class CustomField
  include Mongoid::Document

  field :name,          type: String
  field :model,         type: Symbol
  field :value,         type: String
  field :show_on_table, type: Boolean, default: false

  embedded_in :customizable_field, polymorphic: true
end

所有患者都嵌入了相同的自定义字段。添加自定义字段效果很好。我的疑问是关于更新和销毁。

这可行,但速度很慢。它对每个病人进行查询。理想情况下,我只能对 MongoDB 说“使用 id: 更新文档,该文档嵌入在数组 *custom_fields* 中,用于 Patient 集合中的所有文档”。同理销毁。

如何在 Mongoid 中做到这一点?

我正在使用 Mongoid 3.1.0 和 Rails 3.2.12

【问题讨论】:

    标签: ruby-on-rails mongoid


    【解决方案1】:

    我认为没有一种方法可以在嵌入文档的情况下高效地做到这一点。

    也许您应该考虑在模型之间建立引用关系,以便您可以在集合上使用delete_all 和update_all 方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-03
      • 1970-01-01
      • 1970-01-01
      • 2018-12-31
      • 2021-08-16
      • 2021-02-20
      • 2023-04-01
      • 2018-01-09
      相关资源
      最近更新 更多