Docs Menu

Script Limitations

On this page

  • Constructors
  • Generator Functions
  • Array Sort

The results of database queries cannot be passed inside the following contexts:

  • Class constructor functions
  • Non-async generator functions
  • Callbacks to .sort() on an array

To access to the results of database calls, use async functions, async generator functions, or .map().

The following constructors do not work:

// This code will fail
class FindResults {
constructor() {
this.value = db.students.find();
}
}
// This code will fail
function listEntries() { return db.students.find(); }
class FindResults {
constructor() {
this.value = listEntries();
}
}

Use an async function instead:

class FindResults {
constructor() {
this.value = ( async() => {
return db.students.find();
} )();
}
}
Note

You can also create a method that performs a database operation inside a class as an alternative to working with asynchronous JavaScript.

class FindResults {
constructor() { }
init() { this.value = db.students.find(); }
}

To use this class, first construct a class instance then call the .init() method.

The following generator functions do not work:

// This code will fail
function* FindResults() {
yield db.students.findMany();
}
// This code will fail
function listEntries() { return db.students.findMany(); }
function* findResults() {
yield listEntries();
}

Use an async generator function instead:

function listEntries() { return db.students.findMany(); }
async function* findResults() {
yield listEntries();
}

The following array sort does not work:

// This code will fail
db.getCollectionNames().sort( ( collectionOne, collectionTwo ) => {
return db[ collectionOne ].estimatedDocumentCount() - db[ collectionOne ].estimatedDocumentCount() )
} );

Use .map() instead.

db.getCollectionNames().map( collectionName => {
return { collectionName, size: db[ collectionName ].estimatedDocumentCount() };
} ).sort( ( collectionOne, collectionTwo ) => {
return collectionOne.size - collectionTwo.size;
} ).map( collection => collection.collectionName);

This approach to array sort is often more performant than the equivalent unsupported code.

←  Code ScopingSnippets →
Give Feedback
© 2022 MongoDB, Inc.

About

  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2022 MongoDB, Inc.