Diagram.findTreeRoots in your case will find one of the Groups – it doesn’t know that you only care about Nodes within Groups.
I suggest you do something like:
myDiagram.commit(function(diag) {
diag.findTopLevelGroups().each(function(g) {
var root = null;
var it = g.memberParts.iterator;
while (it.next()) {
var p = it.value;
if (p instanceof go.Node && p.findTreeParentLink() === null) {
root = p;
break;
}
}
if (root) {
root.expandTree();
root.collapseTree(2); // or 3 -- your requirements aren't clear
}
});
}, "collapse to two levels");
I haven’t tried this code, so please pardon me if there are some errors in it.