Q:

How to get dbId of only visible objects in Viewer?

I can get the dbId of all items in the Viewer via
const tree = viewerApp.myCurrentViewer.model.getData().instanceTree;
const dbIndices = Object.values(tree.nodeAccess.dbIdToIndex).slice(1);

But for models imported from Revit, their number is much larger than the actually visible objects in the Viewer (for example, for a project consisting of only three walls, this number is approximately 3,500). How do I get a dbId of only visible objects?

A:

By default all nodes (assets to render for Viewer) are visible when a model is loaded. Each node can be uniquely identified by an unique dbid in addition to its externalId that corresponds to the UniqueID of a Revit component.
So the extra dbids that you observed are actually parent nodes. To isolate them, see here to traverse all the leaf nodes (that is nodes representing a single visible components):
function getAllLeafComponents(viewer, callback) {
    var cbCount = 0; // count pending callbacks
    var components = []; // store the results
    var tree; // the instance tree

    function getLeafComponentsRec(parent) {
        cbCount++;
        if (tree.getChildCount(parent) != 0) {
            tree.enumNodeChildren(parent, function (children) {
                getLeafComponentsRec(children);
            }, false);
        } else {
            components.push(parent);
        }
        if (--cbCount == 0) callback(components);
    }
    viewer.getObjectTree(function (objectTree) {
        tree = objectTree;
        var allLeafComponents = getLeafComponentsRec(tree.getRootId());
    });
}

