Storing a collection of mongoid documents with one operation

44 Views Asked by At

When using Moped gem, I can store an array of hashes with:

users = [{username: "ben", password: "123456", type: "admin" }, {username: "joe", password: "abcd1234" }]
Mongoid::Sessions.default["collection"].insert(users)

With mongoid documents it would look like:

class User
  field :username, type: String
  field :password, type: String
end

users.each { |user_hash| User.create(user_hash) }

Which means an insertion operation for each. Do you know a way to keep the single operation method? Maybe something like a transaction in ActiveRecord?

1

There are 1 best solutions below

0
On BEST ANSWER

You can convert Documents back to Hashes and insert them with single call to #create:

User.create(users.map(&:attributes))