4

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??

Community
  • 1
  • 1
froy001
  • 614
  • 7
  • 21
  • what is this messags in user.messags.collection.insert(batch) ? – Developer Aug 11 '15 at 09:46
  • @Krish `user.messags` is a typo and should read `user.messages` and its the has_many relationship between User and Message. `batch` is just a document array that holds valid documents – froy001 Aug 11 '15 at 10:04
  • ok , that user.messages is a User or user object? can you put here the detailed log and all? – Developer Aug 11 '15 at 10:23
  • user is an instance of User. user.messages is the ( I suppose) the relation object. The log for the operation `user.messages.collection.insert(batch)` is : _{"connectionId"=>2, "n"=>0, "syncMillis"=>0, "writtenTo"=>nil, "err"=>nil, "ok"=>1.0}_ – froy001 Aug 11 '15 at 11:05

2 Answers2

1

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)
tmn4jq
  • 351
  • 1
  • 3
  • 12
0

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) 
D. SM
  • 13,584
  • 3
  • 12
  • 21