ruby-on-railsmongoidmongoid4

How to get all embedded mongoid documents for a user


In Mongoid (Rails) I have 3 models: File, Version and User. Version is embedded_in File, and both File and Version belongs_to a User (though not necessarily the same for all Versions in a File).

Now I want to retrieve all Versions that either belong to a specific User, or are embedded in a File that belongs to the same User.

I have tried:

  1. Pretty much anything Version.<something>, always 0 results (probably because Version is not a top level document?)
  2. File.any_of(user: user, 'versions.user': user): NoMethodError: undefined method `bson_type' for #<User:0x00000007cd9400>
  3. File.any_of(user: user, 'versions.user_id': user.id): Only returns Files that belong to the User, not Files that embed Versions belonging to the user

How can this be achieved in a database friendly way (not fetching all Files and iterating through their Versions)?


Solution

  • When you say 'Embedded', that means the embedded model (Version) is no longer an individual entity and has no separate collection. It is included as a part of the Document (File model object).

    No collection implies -> Pt 1 will return nil

    Pt2 It also implies that the User - Version relationship doesn't exist

    In Pt3 the 'versions.user_id' query is simply ignored.

    Re: "How can this be achieved in a database friendly way?"

    Embedded documents are used only when they are never meant to be used independently or are meaningless without the context of parent document. So the only way to access and embedded doc is through the parent doc.

    Since Version here is being used by both File and User, you should consider creating a separate collection for it. (aka Normalized Data Models)

    You can read up some more on mongodb data modelling here