开发者

GridFS in Ruby: How to upsert?

开发者 https://www.devze.com 2023-01-10 19:30 出处:网络
Does GridFS have an upsert? For example, if i wan开发者_高级运维t to save an image with a specified _id, and one with that same _id already exists, i want it to overwrite (update) it. Otherwise, inse

Does GridFS have an upsert?

For example, if i wan开发者_高级运维t 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.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号