[英]Moped: get id after inserting
當我使用mongo-ruby-driver並插入新文檔時,它返回生成的'_id':
db = MongoClient.new('127.0.0.1', '27017').db('ruby-mongo-examples')
id = db['test'].insert({name: 'example'})
# BSON::ObjectId('54f88b01ab8bae12b2000001')
在使用Moped進行插入后,我試圖獲取文檔的“_id”:
db = Moped::Session.new(['127.0.0.1:27017'])
db.use('ruby-mongo-examples')
id = db['coll'].insert({name: 'example'})
# {"connectionId"=>15, "n"=>0, "syncMillis"=>0, "writtenTo"=>nil, "err"=>nil, "ok"=>1.0}
我如何使用輕便摩托車獲得身份證?
更新:
我也嘗試使用安全模式,但它不起作用:
db = Moped::Session.new(['127.0.0.1:27017'])
db.use('ruby-mongo-examples')
db.with(safe: true) do |safe|
id = safe['coll'].insert({name: 'example'})
# {"connectionId"=>5, "n"=>0, "syncMillis"=>0, "writtenTo"=>nil, "err"=>nil, "ok"=>1.0}
end
插入/保存后,返回的對象將有一個屬性inserted_id
,它是一個BSON::ObjectId
:
# I'm using insert_one
result = safe['coll'].insert_one({name: 'example'})
result.methods.sort # see list of methods/properties
result.inserted_id
result.inserted_id.to_s # convert to string
從這個問題 :
這會很好,但不幸的是Mongo在插入時沒有給我們任何回復(因為它是火和忘記),而在安全模式下,如果它在服務器上生成它仍然不會返回id。 所以除非它是MongoDB的核心功能,否則我們確實沒有任何可能的方法。
您最好的選擇是在插入文檔之前生成id:
document = { _id: Moped::BSON::ObjectId.new, name: "example" }
id = document[:_id]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.