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

Updating an embedded Mongoid::Document updates the array immediately

    XMLWordPrintableJSON

Details

    • Icon: Improvement Improvement
    • Resolution: Unresolved
    • Icon: Unknown Unknown
    • None
    • None
    • None

    Description

      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.

      Attachments

        Activity

          People

            Unassigned Unassigned
            james.kovacs@mongodb.com James Kovacs
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

            Dates

              Created:
              Updated: