Ruby 中的 GridFS:如何更新插入?

发布于 2024-09-13 03:09:24 字数 94 浏览 2 评论 0原文

GridFS 有 upsert 吗?

例如,如果我想保存具有指定 _id 的图像,并且具有相同 _id 的图像已存在,我希望它覆盖(更新)它。否则,将其插入。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

等往事风中吹 2024-09-20 03:09:24

该规范并不是真正为支持更新插入而设计的,因为从技术上讲您正在修改多个文档,并且肯定会出现棘手的竞争条件。所以我们推荐Matt做的事情,就是先删除再放入。

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.

权谋诡计 2024-09-20 03:09:24

我查看了 mongo ruby​​ gem 源代码并发现了这一点:

# 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={})

所以,我在代码中执行了此操作:

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

请参阅此处的工作 sinatra 脚本:
http://github.com/acani/acani-sinatra/ blob/master/acani.rb#L97

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文