GridFS in Ruby: how to upsert?

Does GridFS have upsert?

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

+4
source share
2 answers

The spectrum is really not intended to support upserts, since you are technically modifying more than one document, and, of course, difficult race conditions may arise. Therefore, we recommend what Matt did, which must be removed first and then put down.

+4
source

I looked at the source code for the mongo style gem and found the following:

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

+3
source

All Articles