froy001
froy001

Reputation: 624

Batch insert documents on mongoid relations

I have read the answers here on batch insert e.g. batch insert mongoid

I have 2 collections:

 class User
  include UpdateUserOrCreate
  include Mongoid::Document
  include Mongoid::Timestamps

  has_many :messages, class_name: "Api::V1::Message", autosave: true, validate: false
  has_many :message_export_requests, class_name: "Api::V1::MessageExportRequest", autosave: true, validate: false
end

 class Message
  include Mongoid::Document
  include Mongoid::Timestamps

  belongs_to :user, class_name: "Api::V1::User", autosave: true, foreign_key: :user_id 
end

I have a document array :

batch = [{name: "dsfdf" },{name: "dfsdfh"}]

I am trying to do:

user.messages.collection.insert(batch) 

But the result is that the Message documents are saved with user_id = nil.

How can I batch save the documents in the array through the relation making sure that the foreign key is set??

Upvotes: 4

Views: 887

Answers (2)

D. SM
D. SM

Reputation: 14520

collection returns the driver's collection object. The driver has no knowledge of Mongoid models. You need to set the association links explicitly:

batch = [{name: "dsfdf", user_id: user.id },{name: "dfsdfh", user_id: user.id}]


user.messages.collection.insert(batch) 

Upvotes: 0

tmn4jq
tmn4jq

Reputation: 361

Try this:

user.messages.create(batch)

Also in your case you need to add this to the Message model:

field :name

=== UPDATE === Perhaps this could be useful:

user = ... # get user somehow
batch = [{name: "dsfdf" },{name: "dfsdfh"}].collect { |msg| {name: msg.fetch(:name), user_id: user.id} }
Message.collection.insert(batch)

Upvotes: 1

Related Questions