如何防止mongoid has_many对新对象发出查询

问题描述 投票:0回答:1

我有两个班,A和B

class A
    include Mongoid::Document
    has_many :bs, class_name: "B"
end

class B
    include Mongoid::Document
    belongs_to :a
end

在Rails控制台中,我键入:

a = A.new

它返回

=> #<A _id: 5dab1f7780256231d1bb6da8, > 

太好了,这是一个新记录,所以我知道一个先验,没有b,但是当我键入时:

a.bs

它触发mongo查询:

D, [2019-10-19T10:36:41.867215 #12753] DEBUG -- : MONGODB | Topology type 'unknown' initializing.
D, [2019-10-19T10:36:41.875124 #12753] DEBUG -- : MONGODB | Server localhost:27017 initializing.
D, [2019-10-19T10:36:41.878528 #12753] DEBUG -- : MONGODB | Topology type 'unknown' changed to type 'single'.
D, [2019-10-19T10:36:41.879335 #12753] DEBUG -- : MONGODB | Server description for localhost:27017 changed from 'unknown' to 'standalone'.
D, [2019-10-19T10:36:41.880055 #12753] DEBUG -- : MONGODB | There was a change in the members of the 'single' topology.
D, [2019-10-19T10:36:41.881797 #12753] DEBUG -- : MONGODB | localhost:27017 | test_development.find | STARTED | {"find"=>"bs", "filter"=>{"a_id"=>BSON::ObjectId('5dab1f7780256231d1bb6da8')}}
D, [2019-10-19T10:36:41.884234 #12753] DEBUG -- : MONGODB | localhost:27017 | test_development.find | SUCCEEDED | 0.001728129s

这很疯狂,有什么办法可以防止这种情况?我正在为数百万条记录执行此操作,并且它会触发所有这些不需要的查询。

感谢您的帮助,凯文

ruby-on-rails mongoid
1个回答
0
投票

存在您所遇到的行为的用例:

class A
    include Mongoid::Document
    has_many :bs, class_name: "B"
end

class B
    include Mongoid::Document
    belongs_to :a
end

a = A.create!(id: 1, bs: [B.new])
a.destroy
a = A.new(id: 1)
a.bs
# => [#<B _id: 5dacc787026d7c52b820f0c1, a_id: 1>]

如果您不希望加载关联,则很可能需要调整代码以不查询关联。例如,如果要创建B实例,请使用B.new提供A,而不要通过A.bs

© www.soinside.com 2019 - 2024. All rights reserved.