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

Unable to create correct Mongoid model from JSON

    • Type: Icon: Task Task
    • Resolution: Done
    • Priority: Icon: Major - P3 Major - P3
    • 6.1.1
    • Affects Version/s: None
    • Component/s: None
    • None

      I'm trying to create a Mongoid model from the corresponding JSON structure.

      However it does not include the embedded relation frameworks. I'm using Mongoid 4.0. Am I doing something wrong or is this a bug?

      If I store any embedded relation via store_as under a different name than the default serialization, it works as expected. Also, if I create the model in the database from JSON rather than initialize it everything's fine...

      JSON input

       
      {
        "name": "MyName",
        "frameworks": [
          {
            "name": "grails",
            "runtime": "groovy",
            "versions": []
          }
        ]
      }
      

      Models

        
      require 'mongoid'
      
      class Vendor
        include Mongoid::Document
          include Mongoid::Attributes::Dynamic
      
        # fields
        field :name, type: String
        # relations
        embeds_many :frameworks
        # validations
        validates :name, presence: true
        validates :frameworks, presence: true
      end
      
      class Framework
        include Mongoid::Document
      
        embedded_in :vendor
      
        field :name, type: String
        field :runtime, type: String
        field :versions, type: Array
        # validations
        validates :name, presence: true
        validates :runtime, presence: true
      end
      

      Test App

        
      require 'json'
      require 'require_relative'
      require_relative 'vendor'
      
      begin
        json = JSON.parse(File.read('input.json'))
        @profile= Vendor.new(json)
        puts @profile.inspect
      rescue JSON::ParserError => e
        puts "Error: " << e.to_s
      end
      

            Assignee:
            Unassigned Unassigned
            Reporter:
            stefan-kolb stefan-kolb
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated:
              Resolved: