Jesse Pollak
Jesse Pollak

Reputation: 1600

Mongoid batch insert not using key

I'm using Mongoid for a project and am trying to use the batch insert feature by doing:

Person.collection.insert(friends)

Where friends is an array of hashes.

Unfortunately, I'm trying to use key function of Mongoid to set each object's ID to their Facebook user id. Here is the code:

def process_friends(type, friends)
  unless friends
    @graph = Koala::Facebook::API.new(self.token)

    friends = @graph.get_connections('me','friends', {'fields' => 'id,name,picture,education,location,gender'})
  end

  friends.each do |friend|
    friend[:u_id] = friend["id"]
    friend.delete "id"
  end

  Person.collection.insert(friends)
  self.update_attributes( process_status: {status: "success", type: type})
end

and in my Person model definition:

  key :u_id

It was working when I was looping over all the friends and adding them individually, but now that I've gone to a batch insert it's not setting each Person's id to the u_id.

Any ideas?

Upvotes: 1

Views: 441

Answers (1)

Tyler Brock
Tyler Brock

Reputation: 30146

Model.collection retrieves the internal (ruby driver) collection instead of using mongoid. Batch insert needs to be done that way because it is not supported by mongoid itself.

Essentially, by accessing the collection directly, you are bypassing mongoid and so the fact that you declare key :u_id doesn't (and shouldn't) have any effect.

The solution is to just use _id instead of u_id so that the driver doesn't try to generate one for you.

friends.each do |friend|
  friend[:_id] = friend["id"]
  friend.delete "id"
end

However, this may have implications elsewhere in your code.

Another solution, if you are lazy, is to just not care about the extra object_id and let the driver create one for you.

Upvotes: 2

Related Questions