mongomapper association skips duplicates

2019-03-06 12:12发布

问题:

I have a Document with Array of ObjectId:

Class Task
  key :user_id, Array
  many :userlist, class_name: 'User', :in => :user_id

In that Array I store different user_id values, sometimes duplicated. I can see duplicated user_id's using:

@task.user_id.each do |z|
  puts z
end

But when I fetch and associate the data using:

@task.userlist.each do |z|
  puts z.name
end

I do not get the duplicates :(, only unique id's get associated. Why?

回答1:

What you are seeing is exactly correct from the definition of associations and the underlying query matching the "in" clause. Refresh you thinking of "in" as "in the set" of distinct objects http://en.wikipedia.org/wiki/Set_(mathematics) The fetch for userlist has an underlying query on the User collection with a $in clause, see http://docs.mongodb.org/manual/reference/operator/query/in/

For the @task.userlist association, you will get only the documents in the User collection that match the $in clause, the User collection is the primary "subject." There's a significant semantic difference from

User.where(:user_id.in => self.user_id)

versus

self.user_id.collect |user_id| do User.where(:user_id => user_id).first; end

In order to get "duplicates" from the former query, you would have to have duplicate documents in the User collection, seriously. ;-)

Hope that this helps your understanding.