Uploaded image for project: 'Mongoid'
  1. Mongoid
  2. MONGOID-5519

Updating an embedded Mongoid::Document updates the array immediately

    • Type: Icon: Improvement Improvement
    • Resolution: Unresolved
    • Priority: Icon: Unknown Unknown
    • None
    • Affects Version/s: None
    • Component/s: None

      Consider the following posts.rb and comment.rb models:

      class Post
        include Mongoid::Document
        include Mongoid::Timestamps
      
        field :title, type: String
        field :body, type: String
        field :ratings, type: Array
      
        embeds_many :comments
      end
      
      class Comment
        include Mongoid::Document
        include Mongoid::Timestamps
      
        field :name, type: String
        field :message, type: String
      
        embedded_in :post
      end
      

      If you update the Post.comments collection by pushing a new comment onto the array, the database is immediately updated without having to call post.save:

      post = Post.first
      post.comments.push(Comment.new(name: “Bob”, message: “Awesome post”))
      

      If updates were made to the post prior to pushing the comment, only the new comment is added to the comments array, not any updates made to the parent Post object.

      This broke my mental model of an ODM where multiple changes are performed in memory and those changes are only persisted when I call post.save. If this is intended and expected, we should clearly document how embedded Mongoid::Document objects behave compared to an array of plain old Ruby classes. We should also clearly explain when and when not to use an embedded array of Mongoid::Document versus a plain old Ruby class.

            Assignee:
            Unassigned Unassigned
            Reporter:
            james.kovacs@mongodb.com James Kovacs
            Votes:
            1 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated: