【问题标题】:Storing jsonb data through ecto通过ecto存储jsonb数据
【发布时间】:2018-10-09 04:02:20
【问题描述】:

我正在尝试通过 ecto 将 jsonb 数据传递到 postgres。我希望能够获取一个有效的 JSON 字符串,将其添加为 graphql 参数,然后在我的表中查看该 json。

迁移

defmodule MyApp.CreateJsonTable do
  use Ecto.Migration

  def change do
    create table(:geodata) do
      add(:json, :map)

      timestamps(type: :utc_datetime)
    end
  end
end

我的理解是你需要为 JSONB 定义一个 Poison 结构体,然后在插入时解码成它。

defmodule Geodatajson do
  use MyApp, :model

  embedded_schema do
    field(:latitude, :float)
    field(:longitude, :float)
  end
end

现在是模型:

defmodule MyApp.Geodata do
  use MyApp, :model

  alias MyApp.Repo
  alias MyApp.Geodata

  schema "geodata" do
    embeds_one(:json, Geodatajson)

    timestamps()
  end

  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [:json])
  end

  def add_geodata(str) do
    json = str |> Poison.decode!(as: Geodatajson)
    data = %Geodata{json: json}
    Repo.insert(data)
  end
end

我尝试像这样传递数据:

iex> MyApp.Geodata.add_geodata("{\"latitude\": 1.23, \"longitude\": 4.56}")

但是 JSONB 没有被解码:

{:ok,
 %MyApp.Geodata{
   __meta__: #Ecto.Schema.Metadata<:loaded, "geodata">,
   id: 26,
   inserted_at: ~N[2018-04-28 13:28:42.346382],
   json: %Geodatajson{
     id: "3b22ef94-92eb-4c64-8174-9ce1cb88e8c5",
     latitude: nil,
     longitude: nil
   },
   updated_at: ~N[2018-04-28 13:28:42.346392]
 }}

如何将这些数据导入 postgres?

【问题讨论】:

    标签: postgresql elixir ecto jsonb


    【解决方案1】:

    Poison 的as: 要求您传递一个结构实例,而不仅仅是模块的名称。

    json = str |> Poison.decode!(as: Geodatajson)
    

    应该是:

    json = str |> Poison.decode!(as: %Geodatajson{})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-02
      • 1970-01-01
      相关资源
      最近更新 更多