Running custom commands in mongodb node driver

368 views Asked by At

I am in need of creating a code to hide/unhide mongo index in node. There are no such methods on node-mongodb-native although they exist on mongo shell.

Second attempt was to run a custom command, but await db.command({ hideIndex: 'some_name' }) ended up with MongoServerError: no such command: 'hideIndex'.

Lastly, I am aware that in older versions there were execute/eval methods, but it looks like they were removed at some point. I know it poses some security issues allowing someone to run custom commands, but I don't believe no one ever needed something custom to be run from node with the list of methods available in driver being so limited?

Which raises a question: how does one run a custom command in node mongodb driver?

1

There are 1 answers

1
dododo On BEST ANSWER

The error directly says what happens, there is no such command. Mongosh has just a wrapper over few more commands to reach behavior you need and this helper doesn't exist in other drivers (at least in most of them). You can check inner steps that executed by hideIndex shell helper (by launching this helper without ()) and did them too in the node via runCommand (in node it's called just command)

    MongoDB Enterprise replset:PRIMARY> db.coll.hideIndex
    function(index) {
        return this._hiddenIndex(index, true);
    }
    MongoDB Enterprise replset:PRIMARY> db.coll._hiddenIndex
    function(index, hidden) {
        assert(index, "please specify index to hide");

        // Need an extra check for array because 'Array' is an 'object', but not every 'object' is an
        // 'Array'.
        var indexField = {};
        if (typeof index == "string") {
            indexField = {name: index, hidden: hidden};
        } else if (typeof index == "object") {
            indexField = {keyPattern: index, hidden: hidden};
        } else {
            throw new Error("Index must be either the index name or the index specification document");
        }
        var cmd = {"collMod": this._shortName, index: indexField};
        var res = this._db.runCommand(cmd);
        return res;
    }