@@ -2,15 +2,16 @@ import { Document } from "mongodb";
22import { NodeDriverServiceProvider } from "@mongosh/service-provider-node-driver" ;
33import { ErrorCodes , MongoDBError } from "../errors.js" ;
44
5-
65/**
76 * Check if the query plan uses an index
87 * @param explainResult The result of the explain query
98 * @returns true if an index is used, false if it's a full collection scan
109 */
1110export function usesIndex ( explainResult : Document ) : boolean {
12- const stage = explainResult ?. queryPlanner ?. winningPlan ?. stage ;
13- const inputStage = explainResult ?. queryPlanner ?. winningPlan ?. inputStage ;
11+ const queryPlanner = explainResult ?. queryPlanner as Document | undefined ;
12+ const winningPlan = queryPlanner ?. winningPlan as Document | undefined ;
13+ const stage = winningPlan ?. stage as string | undefined ;
14+ const inputStage = winningPlan ?. inputStage as Document | undefined ;
1415
1516 // Check for index scan stages (including MongoDB 8.0+ stages)
1617 const indexScanStages = [
@@ -20,14 +21,14 @@ export function usesIndex(explainResult: Document): boolean {
2021 "EXPRESS_CLUSTERED_IXSCAN" ,
2122 "EXPRESS_UPDATE" ,
2223 "EXPRESS_DELETE" ,
23- "IDHACK"
24+ "IDHACK" ,
2425 ] ;
2526
26- if ( indexScanStages . includes ( stage ) ) {
27+ if ( stage && indexScanStages . includes ( stage ) ) {
2728 return true ;
2829 }
2930
30- if ( inputStage && indexScanStages . includes ( inputStage . stage ) ) {
31+ if ( inputStage && inputStage . stage && indexScanStages . includes ( inputStage . stage as string ) ) {
3132 return true ;
3233 }
3334
@@ -65,7 +66,10 @@ export async function checkIndexUsage(
6566 const explainResult = await explainCallback ( ) ;
6667
6768 if ( ! usesIndex ( explainResult ) ) {
68- throw new MongoDBError ( ErrorCodes . ForbiddenCollscan , getIndexCheckErrorMessage ( database , collection , operation ) ) ;
69+ throw new MongoDBError (
70+ ErrorCodes . ForbiddenCollscan ,
71+ getIndexCheckErrorMessage ( database , collection , operation )
72+ ) ;
6973 }
7074 } catch ( error ) {
7175 if ( error instanceof Error && error . message . includes ( "Index check failed" ) ) {
@@ -76,4 +80,4 @@ export async function checkIndexUsage(
7680 // This avoids blocking normal queries in special cases (e.g., permission issues)
7781 console . warn ( `Index check failed to execute explain for ${ operation } on ${ database } .${ collection } :` , error ) ;
7882 }
79- }
83+ }
0 commit comments