How to create a collection correctly in MongoDB to avoid "ReferenceError: Not defined" error?

To create a collection correctly in MongoDB and avoid "ReferenceError: Not defined" errors, you must use the proper MongoDB database object syntax with createCollection() method.

Syntax

db.createCollection("collectionName");

Example: Creating a Collection

Let us create a collection called "employeeInformation" in the "sample" database ?

use sample;
db.createCollection("employeeInformation");
switched to db sample
{ "ok" : 1 }

Verify Collection Creation

Display all collections in the current database to confirm the collection was created ?

db.getCollectionNames();
[
  "arraySizeErrorDemo",
  "atleastOneMatchDemo",
  "basicInformationDemo",
  "combinedAndOrDemo",
  "convertSQLQueryDemo",
  "copyThisCollectionToSampleDatabaseDemo",
  "countOrSizeDemo",
  "distinctOnMultipleFieldsDemo",
  "documentWithAParticularFieldValueDemo",
  "employee",
  "employeeInformation",
  "findListOfIdsDemo",
  "findMimimumElementInArrayDemo",
  "findSubstring",
  "getAllRecordsFromSourceCollectionDemo",
  "getElementWithMaxIdDemo",
  "insertDocumentWithDateDemo",
  "internalArraySizeDemo",
  "keepTwoColumnsUniqueDemo",
  "largestDocumentDemo",
  "makingStudentInformationClone",
  "nestedArrayDemo",
  "oppositeAddToSetDemo",
  "prettyDemo",
  "projectionAnElementDemo",
  "replacingEntireDocumentDemo",
  "returnOnlyUniqueValuesDemo",
  "searchInInnerDemo",
  "selectItemDemo",
  "selectWhereInDemo",
  "sourceCollection",
  "specificFieldDemo",
  "studentInformation",
  "sumOfValueDemo",
  "sumTwoFieldsDemo",
  "truncateDemo",
  "updateFieldIfValueIsGreaterDemo",
  "updateInformation",
  "updateSubObjectDemo",
  "userInformation"
]

Key Points

  • Always use db object to reference the current database
  • Collection names must be enclosed in quotes
  • The createCollection() method returns { "ok" : 1 } on success

Conclusion

Use db.createCollection("name") with the proper MongoDB database object to avoid reference errors. Always ensure you're connected to the correct database using use databaseName before creating collections.

Updated on: 2026-03-15T01:07:24+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements