ruby on rails - Mongoid upsert with a different key -
is possible upsert mongodb collection json/hash of fields, instead of using _id
objectid field, use different indexed field such external_id
?
i using update items receive feed on daily basis, , such, feed items don't contain internal id.
yes, possible upsert custom id in mongoid, in 3.0.0.rc circa june 27, 2012.
app/models/item.rb
class item include mongoid::document field :external_id, type: string field :_id, type: string, default: ->{ external_id } field :text, type: string end
test/unit/item_test.rb
require 'test_helper' class itemtest < activesupport::testcase def setup item.delete_all end test "external id" item.new( text: 'lorem ipsum' ).upsert item.new( external_id: 'an external id', text: 'dolor sit amet' ).upsert puts item.all.to_a.collect{|item|item.inspect} end end
output
run options: --name=test_external_id
# running tests: #<item _id: 4ff202501f98ce8202c03268, _type: nil, external_id: nil, text: "lorem ipsum"> #<item _id: external id, _type: nil, external_id: "an external id", text: "dolor sit amet"> . finished tests in 0.028232s, 35.4208 tests/s, 0.0000 assertions/s. 1 tests, 0 assertions, 0 failures, 0 errors, 0 skips
to have install github, visit , clone from
https://github.com/mongoid/mongoid bundle install bundle exec rake install
here's link commit makes possible.
https://github.com/mongoid/mongoid/commit/3062363bad3ab947d7689502d6805652b20e89a0
Comments
Post a Comment