ma11hew28
ma11hew28

Reputation: 126457

GridFS in Ruby: How to upsert?

Does GridFS have an upsert?

For example, if i want to save an image with a specified _id, and one with that same _id already exists, i want it to overwrite (update) it. Otherwise, insert it.

Upvotes: 4

Views: 1164

Answers (2)

Kyle Banker
Kyle Banker

Reputation: 4359

The spec isn't really designed to support upserts, since you're technically modifying more than one document, and certainly tricky race conditions can arise. So we recommend what Matt has done, which is to delete first and then put.

Upvotes: 4

ma11hew28
ma11hew28

Reputation: 126457

I looked at the mongo ruby gem source code and found this:

# Store a file in the file store. This method is designed only for writing new files;
# if you need to update a given file, first delete it using #Grid#delete.
# ...
def put(data, opts={})

So, I did this in the code:

grid.delete(id) # if exists  
grid.put(tmp_file.read, :_id => id, :content_type => file_type)

See the working sinatra script here: http://github.com/acani/acani-sinatra/blob/master/acani.rb#L97

Upvotes: 3

Related Questions