gpt4 book ai didi

ruby - 如何处理 mongodb 在 ruby​​ 中的 E11000 重复键错误

转载 作者:可可西里 更新时间:2023-11-01 09:59:20 24 4
gpt4 key购买 nike

在ruby中有没有处理mongodb相关异常的好例子?在这种情况下,我有:

/home/askar/.rvm/gems/ruby-1.9.3-p429/gems/mongo-1.8.6/lib/mongo/networking.rb:89:in `send_message_with_gle': 11000: E11000 duplicate key error index: somedb.somecoll.$_id_  dup key: { : "some_id" } (Mongo::OperationFailure)
from /home/askar/.rvm/gems/ruby-1.9.3-p429/gems/mongo-1.8.6/lib/mongo/collection.rb:1108:in `block in insert_documents'
from /home/askar/.rvm/gems/ruby-1.9.3-p429/gems/mongo-1.8.6/lib/mongo/util/logging.rb:33:in `block in instrument'
from /home/askar/.rvm/gems/ruby-1.9.3-p429/gems/mongo-1.8.6/lib/mongo/util/logging.rb:65:in `instrument'
from /home/askar/.rvm/gems/ruby-1.9.3-p429/gems/mongo-1.8.6/lib/mongo/util/logging.rb:32:in `instrument'
from /home/askar/.rvm/gems/ruby-1.9.3-p429/gems/mongo-1.8.6/lib/mongo/collection.rb:1106:in `insert_documents'
from /home/askar/.rvm/gems/ruby-1.9.3-p429/gems/mongo-1.8.6/lib/mongo/collection.rb:375:in `insert'
from lib/tasks/getorders.rb:47:in `block in <main>'
from lib/tasks/getorders.rb:25:in `each'
from lib/tasks/getorders.rb:25:in `<main>'

我遇到这个错误是因为我试图插入一个文档,其 id 已经存在于 mongodb 数据库中,我只想知道如何在 ruby​​ 中处理与 mongodb 相关的异常。例如,如果发生异常,那么我会更改哈希的 id,然后重新尝试插入它。

rescue block 会是什么样子?

最佳答案

ruby block 看起来像这样:

begin
# your operation
rescue Mongo::OperationFailure => e
if e.message =~ /^11000/
puts "Duplicate key error #{$!}"
# do something to recover from duplicate
else
raise e
end
end
# the rest of the exceptions follow ..
# if you just care about the dup error
# then ignore them
#rescue Mongo::MongoRubyError
# #Mongo::ConnectionError, Mongo::ConnectionTimeoutError, Mongo::GridError, Mongo::InvalidSortValueError, Mongo::MongoArgumentError, Mongo::NodeWithTagsNotFound
# puts "Ruby Error : #{$!}"
#rescue Mongo::MongoDBError
# # Mongo::AuthenticationError, Mongo::ConnectionFailure, Mongo::InvalidOperation, Mongo::OperationFailure
# puts "DB Error : #{$!}"
#rescue Mongo::OperationTimeout
# puts "Socket operation timeout Error : #{$!}"
#rescue Mongo::InvalidNSName
# puts "invalid collection or database Error : #{$!}"
#end

但是,如果您正在更新一条已经存在的记录,为什么不使用 upsert .

如果您正在创建新记录,那么为什么不让 mongod 创建 _id 呢?

关于ruby - 如何处理 mongodb 在 ruby​​ 中的 E11000 重复键错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16930311/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com