0

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 Answer 1

2

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;
    }
Sign up to request clarification or add additional context in comments.

1 Comment

That is exactly what I was looking for, didn't know/think of I could look into the sources like this. It worked as a charm! Thanks so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.