Uploaded image for project: 'Ruby Driver'
  1. Ruby Driver
  2. RUBY-2783

Return a String without "$oid" from BSON::ObjectId#as_json and #to_json

    • Type: Icon: Improvement Improvement
    • Resolution: Fixed
    • Priority: Icon: Unknown Unknown
    • bson-5.0.0
    • Affects Version/s: None
    • Component/s: BSON
    • Labels:
      None
    • Major Change

          1. The Change

      Currently, `BSON::ObjectId#as_json` will return `{ "$oid" => "03d623ca58edf9046e207565" }`

      This PR does what 99% of users prefer: return a plain String `"03d623ca58edf9046e207565"`

      I've included a "Breaking change" notice in the docs for this.

          1. Why

      While `$oid` may be the correct way to represent an ObjectID in strict "BSON", it is not a practical way to represent an ObjectID in "JSON" as used in real world apps. The standard use case for JSON (`.as_json` method) is *to serialize objects for HTTP APIs*. The primary goal of Mongoid is for us as developers not to have to worry about BSON internal representations; instead we think in terms of the Ruby app domain. (Mongoid / Mongo Ruby Driver handles the BSON nuts-and-bolts for us.)

          1. Other Ideas

      We could also add `BSON::ObjectId#as_bson` and `Object#as_bson` (which delegates to `.as_json` in all cases except `ObjectId`.) I don't think it's particularly useful, but I'd be happy to implement it if the Mongo team would like. (We'd probably want to call `mongoize` or `evolve` as well...)

          1. More Background

      The current behavior drives Rails users absolutely crazy as you can see in the following issues, and *nearly everyone ends up monkey-patching this method* after hours of debugging frustration. Here are some a few examples out of hundreds:

      Incidentally, Mongoid 3.1 and earlier used to serialize this as a String; when it changed to `$oid` it broke my and many other users apps--this unexpected behavior causes lots of bugs.

            Assignee:
            oleg.pudeyev@mongodb.com Oleg Pudeyev (Inactive)
            Reporter:
            shields@tablecheck.com Johnny Shields
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated:
              Resolved: