mongodb-labs / mongosh-snippets

An experimental plugin feature for mongosh
32 stars 20 forks source link

tojson() does not work for MinKey/MaxKey #3

Closed Wernfried closed 2 months ago

Wernfried commented 2 years ago

Function tojson() does not work for MinKey/MaxKey values:

x = {min: MinKey, max: 100}
{
  min: [Function: MinKey] {
    fromExtendedJSON: [Function (anonymous)],
    toBSON: [Function: toBSON],
    help: [Function (anonymous)] Help
  },
  max: 100
}

print(tojsononeline(x))
Uncaught:
TypeError: x.tojson is not a function
    at /home/mediation/mongotypes.js:58:3805
    at tojson (/home/mediation/mongotypes.js:58:4196)
    at /home/mediation/mongotypes.js:61:729
    at tojsonObject (/home/mediation/mongotypes.js:62:283)
    at /home/mediation/mongotypes.js:58:3257
    at tojson (/home/mediation/mongotypes.js:58:4196)
    at /home/mediation/mongotypes.js:58:263
    at tojsononeline (/home/mediation/mongotypes.js:58:440)
    at REPL3:34:243
    at REPL3:48:5

In legacy mongo shell it works fine:

> x = {min: MinKey, max: 100}
{ "min" : { "$minKey" : 1 }, "max" : 100 }
> print(tojsononeline(x))
{  "min" : { "$minKey" : 1 },  "max" : 100 }

Any idea how to fix it?

Kind Regards Wernfried

Wernfried commented 1 year ago

Please see my proposal to fix the issue:

tojson = function(x, indent, nolint, depth) {
    if (x === null)
        return "null";

    if (x === undefined)
        return "undefined";

    if (!indent)
        indent = "";

    if (typeof depth !== 'number') {
        depth = 0;
    }

    switch (typeof x) {
        case "string":
            return JSON.stringify(x);
        case "number":
        case "boolean":
            return "" + x;
        case "object": {
            var s = tojsonObject(x, indent, nolint, depth);
            if ((nolint == null || nolint == true) && s.length < 80 &&
                (indent == null || indent.length == 0)) {
                s = s.replace(/[\t\r\n]+/gm, " ");
            }
            return s;
        }
        case "function":
            if (x === MinKey ) return tojson({ "$minKey" : 1 });
            if (x === MaxKey ) return tojson({ "$maxKey" : 1 });
            return x.toString();
        default:
            throw Error("tojson can't handle type " + (typeof x));
    }
};
Wernfried commented 2 months ago

Created a PR: https://github.com/mongodb-labs/mongosh-snippets/pull/9/commits/2dbdab54f945c1b24931fd3853bffbfc5a409c11