Compare string ID to BSON::ObjectId

冷暖自知 提交于 2019-12-22 08:04:48

问题


I have an array of made up of type BSON::ObjectId and I want it to compare against some IDs as strings.

if my_array_of_BSON_ObjectIds.include?(@my_id_as_a_string)
   # delete the item from the array
else
   # add the item to the array as a BSON::ObjectId
end

This is not working as the types are different, can I turn my string into a BSON::ObjectId? If so, how?


回答1:


You can use BSON::ObjectId(@my_id_as_a_string) for representation your id as BSON::ObjectId

refs http://api.mongodb.org/ruby/current/BSON.html#ObjectId-class_method




回答2:


Mongoid 2.x with 10gen's driver:

BSON::ObjectId.new('506144650ed4c08d84000001')

Mongoid 3 with moped:

Moped::BSON::ObjectId.from_string('506144650ed4c08d84000001')

Mongoid 4 (moped) / Mongoid 5/6/7 (mongo):

BSON::ObjectId.from_string('506144650ed4c08d84000001')



回答3:


collection.delete_one({"_id"=>BSON::ObjectId(params['id'])})

This worked for me and it deleted the record from the database successfully



来源:https://stackoverflow.com/questions/12578828/compare-string-id-to-bsonobjectid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!