ObjectId getTimestamp helper throws an error

XMLWordPrintableJSON

    • Type: Bug
    • Resolution: Won't Fix
    • Priority: Major - P3
    • No version
    • Affects Version/s: None
    • Component/s: sh, snippets
    • None
    • Environment:
      OS:
      node.js / npm versions:
      Additional info:
    • 2
    • Not Needed

      Using mongosh 1.6.0 the following code will fail:

      (new ObjectId()).getTimestamp()
      // TypeError: Cannot read properties of undefined (reading 'slice')
      

      The above does work with the legacy shell and appears to be due to the implementation of ObjectId.prototype.getTimestamp calling ObjectId.prototype.valueOf, which returns undefined (instead of a string).

      This can be fixed by changing ObjectId.prototype.getTimestamp to:

      ObjectId.prototype.getTimestamp = function() {  
        if (this.toHexString) return new Date(parseInt(this.toHexString().slice(0, 8), 16) * 1000);  
        return new Date(parseInt(this.toString('hex').slice(0, 8), 16) * 1000);
      };
      

              Assignee:
              Gaurab Aryal
              Reporter:
              Alex Bevilacqua
              Votes:
              0 Vote for this issue
              Watchers:
              4 Start watching this issue

                Created:
                Updated:
                Resolved: