dersar00
Save data to mongodb through code
Hello.
I using Mongo.Ecto to mongodb connection, when I run in CLI commands:
person = %Friends.Person{}
Friends.Repo.insert(person)
I got result and a record is created. But with same commands in code I can’t do it. How do it?
Repository with full proj:
https://github.com/dersar00/friends
Most Liked
kokolegorille
Friend is a module… it should contains functions You can call.
In your code…
defmodule Friends do
IO.puts "start"
person = %Friends.Person{}
Friends.Repo.insert(person)
IO.puts "saved"
end
it could be
defmodule Friends do
def save_a_new_person() do
IO.puts "start"
person = %Friends.Person{}
Friends.Repo.insert(person)
IO.puts "saved"
end
end
And then You can call it like this
iex> Friends.save_a_new_person()
Why would You expect your code in the module to run? or when?
idi527
As @kokolegorille has already pointed out, you shouldn’t run db commands outside of functions, since then they would be executed during compilation before the database connection process is started.
Put those commands in a function, and execute the function when you need to. It can be in response to a controller action or whatever else.
Also maybe read through the official elixir guide to get a better understanding of how elixir modules and functions work.







