File tree Expand file tree Collapse file tree 3 files changed +46
-0
lines changed
Expand file tree Collapse file tree 3 files changed +46
-0
lines changed Original file line number Diff line number Diff line change @@ -735,6 +735,14 @@ describe('e2e', function () {
735735 ) ;
736736 } ) ;
737737
738+ it ( 'throws the .toArray() suggestion when a user attempts to serialize a cursor' , async function ( ) {
739+ await shell . executeLine ( 'const b = db.test.find()' ) ;
740+ await shell . executeLine ( 'console.log(JSON.stringify(b));' ) ;
741+ shell . assertContainsOutput (
742+ 'Cannot serialize a cursor to JSON. Did you mean to call .toArray() first?'
743+ ) ;
744+ } ) ;
745+
738746 it ( 'expands explain output from aggregation indefinitely' , async function ( ) {
739747 await shell . executeLine (
740748 'explainOutput = db.test.aggregate([{ $limit: 1 }], {explain: "queryPlanner"})'
Original file line number Diff line number Diff line change @@ -793,6 +793,29 @@ describe('Cursor', function () {
793793 } ) ;
794794 } ) ;
795795
796+ describe ( '#toJSON' , function ( ) {
797+ let spCursor : StubbedInstance < ServiceProviderCursor > ;
798+ let shellApiCursor : Cursor ;
799+
800+ beforeEach ( function ( ) {
801+ spCursor = stubInterface < ServiceProviderCursor > ( ) ;
802+ shellApiCursor = new Cursor ( mongo , spCursor ) ;
803+ } ) ;
804+
805+ it ( 'throws with the .toArray() suggestion' , function ( ) {
806+ try {
807+ JSON . stringify ( shellApiCursor ) ;
808+ expect . fail ( 'expected error' ) ;
809+ } catch ( e : any ) {
810+ expect ( e ) . to . be . instanceOf ( MongoshInvalidInputError ) ;
811+ expect ( e . message ) . to . contain (
812+ 'Cannot serialize a cursor to JSON. Did you mean to call .toArray() first?'
813+ ) ;
814+ expect ( e . code ) . to . equal ( CommonErrors . InvalidArgument ) ;
815+ }
816+ } ) ;
817+ } ) ;
818+
796819 describe ( '#maxScan' , function ( ) {
797820 let spCursor : StubbedInstance < ServiceProviderCursor > ;
798821 let shellApiCursor : Cursor ;
Original file line number Diff line number Diff line change @@ -34,6 +34,21 @@ export default class Cursor extends AggregateOrFindCursor<ServiceProviderFindCur
3434 super ( mongo , cursor ) ;
3535 }
3636
37+ /**
38+ * Throw a custom exception when a user attempts to serialize a cursor,
39+ * pointing to the fact that .toArray() needs to be called first.
40+ *
41+ * @param {CursorFlag } flag - The cursor flag.
42+ *
43+ * @returns {void }
44+ */
45+ toJSON ( ) : void {
46+ throw new MongoshInvalidInputError (
47+ 'Cannot serialize a cursor to JSON. Did you mean to call .toArray() first?' ,
48+ CommonErrors . InvalidArgument
49+ ) ;
50+ }
51+
3752 /**
3853 * Add a flag and return the cursor.
3954 *
You can’t perform that action at this time.
0 commit comments