【问题标题】:How to globally override Mongoid::Document._id generation如何全局覆盖 Mongoid::Document._id 生成
【发布时间】:2016-03-14 20:19:31
【问题描述】:

我想覆盖 mongoid 中的 _id 生成类型(另一个共享数据库的应用程序使用 String 而不是 ObjectId()

我可以通过添加这个来为每个模型做到这一点:

    field :_id, type: String, default: -> { BSON::ObjectId.new.to_s }

但是如何全局附加它以保持干燥?

【问题讨论】:

  • 您忘记添加您正在使用的 mongoid 版本。 TBH,我认为这样做没有意义。你想用这个实现什么?
  • 版本 5.1.x。我想将我的RoR 应用程序连接到托管mongoDbmeteor。而这个meteor app 将 mongoDb ObjectId 写为字符串。如果我不覆盖mongoid _id,它将不会获取由流星应用程序创建的条目。

标签: ruby-on-rails ruby mongodb mongoid


【解决方案1】:

非常有效的用例,但 looking into the code 你可能在 Mongoid::Fields 上不走运,但你可以覆盖应该像这样的 mongoize

Item.new.id
 => BSON::ObjectId('56e727892ada693ea8000000')

class BSON::ObjectId
  def self.mongoize(k)
    k.to_s
  end
end

Item.new.id
 => "56e7276f2ada693737000002"

【讨论】:

  • 嗯,似乎可以工作,但Item.find(params[:id]) 不再工作了。 message: Document(s) not found for class User with id(s) 56e728dfa54d752083e7435a. summary: When calling User.find with an id or array of ids, each parameter must match a document in the database or this error will be raised. The search was for the id(s): 56e728dfa54d752083e7435a ... (1 total) and the following ids were not found: 56e728dfa54d752083e7435a.
  • 您的 metor 应用程序有多久了?我之所以问,是因为 Metor 中有一个选项可以正确存储 id 而不仅仅是字符串:docs.meteor.com/#/full/meteor_collection
  • 它是新的。在您建议更新后,我创建了一个新的(1.2.1):这是一个要点gist.github.com/mediatainment/b451b021fbb34e61f3f6
  • 我发现,不允许覆盖流星的users-collection。 meteor-accounts 他们用strings 提供id 生成,并且不允许ObjectIds。但是所有其他 Meteor 收藏都可以简单地删除Users = new Mongo.Collection('users', {idGeneration: 'MONGO'});。这很烦人!
猜你喜欢
  • 2020-07-28
  • 2014-09-27
  • 1970-01-01
  • 1970-01-01
  • 2019-05-21
  • 2013-07-10
  • 1970-01-01
  • 1970-01-01
  • 2013-05-27
相关资源
最近更新 更多