比较字符串ID和BSON::ObjectId

5

我有一个由类型为 BSON::ObjectId 的数组,我想将其与一些字符串形式的ID进行比较。

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

由于类型不同,这并不起作用,我能把我的字符串转换成 BSON::ObjectId 吗?如果可以,怎么做?

4个回答

14

Mongoid 2.x与10gen的驱动程序:

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

使用Moped的Mongoid 3:

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

Mongoid 4(moped)/ Mongoid 5/6/7(mongo):
BSON::ObjectId.from_string('506144650ed4c08d84000001')

3
这段话的意思是:“BSON::ObjectId.from_string('506144650ed4c08d84000001')可以运行,但在Mongoid 4中无法使用。” - Dex
1
BSON::ObjectId.from_string('506144650ed4c08d84000001') 在 Rails 5 和 Mongoid 7 上适用。也可参考 https://www.rubydoc.info/github/mongodb/bson-ruby/BSON/ObjectId - CyberMew
1
@CyberMew:哇,mongoid 7?我连6都还没用呢。 :/ - Sergio Tulentsev

5

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

这对我有用,它成功地从数据库中删除了记录


0

有一种更短的方式:

BSON::ObjectId("id_here")

但对于您的情况,将对象映射到ID然后进行比较会更容易:

if my_array_of_BSON_ObjectIds..map(&:to_s).include?(@my_id_as_a_string)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接