Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to save data from a json array to the database MongoDB?
    primarykey
    data
    text
    <p>How to save the marker coordinates received as json parameter and build it to lat and lng fields with right values? I tried to do this in many ways but it gave everyone fails. Below those that are closest in my opinion good.</p> <pre><code>#controller: def create @user = User.new() received_json = ["{\"lat\":52.38521483550798,\"lng\":16.866459809082016}", "{\"lat\":52.40458894240522,\"lng\":16.856503449218735}", "{\"lat\":52.42605757375466,\"lng\":16.86989303662108}"] # objArray=JSON.parse(received_json.to_json) objArray=ActiveSupport::JSON.decode(received_json.to_json) #example 1 objArray.each do |obj| @user.markers.build(obj) end # NoMethodError (undefined method `each_pair' for "{\"lat\":52.38521483550798,\"lng\":16.866459809082016}":String): #example 2 objArray.each do |obj, value| @user.markers.build(obj=&gt;value) end # BSON::InvalidKeyName ({"lat":52.38521483550798,"lng":16.866459809082016} - key must not contain '.'): #example 3 objArray.each do |obj| @user.markers.build(lat:obj) end # This approach save data but in one field lat in user markers array # Data Saved: {"_id":"4e9eac161e7bf208280002fb","markers":[{"_id":"4e9eac161e7bf208280002fc","lat":"{\"lat\":52.38521483550798,\"lng\":16.866459809082016}"},{"_id":"4e9eac161e7bf208280002fd","lat":"{\"lat\":52.40458894240522,\"lng\":16.856503449218735}"},{"_id":"4e9eac161e7bf208280002fe","lat":"{\"lat\":52.42605757375466,\"lng\":16.86989303662108}"}]} end #model class User include Mongoid::Document field :name, :type =&gt; String embeds_many :markers, :inverse_of =&gt; :user end class Marker include Mongoid::Document field :lat, :type =&gt; Float field :lng, :type =&gt; Float embedded_in :user, :inverse_of =&gt; :marker end </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload