Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

สร้าง Collection ใน MongoDB ให้ถูกต้อง หลีกเลี่ยง ReferenceError: Not Defined

ข้อผิดพลาด ReferenceError: ... is not defined มักเกิดจากการพยายามเรียกใช้ Collection โดยตรงโดยไม่ผ่าน Object db ต้องใช้ db.createCollection() เสมอ

วิธีที่ถูกต้อง

db.createCollection("yourCollectionName");

ตัวอย่าง: สร้าง Collection ชื่อ employeeInformation

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

แสดงรายชื่อ Collections เพื่อยืนยัน

> db.getCollectionNames();

ผลลัพธ์ (employeeInformation อยู่ในรายการ):

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

สาเหตุ Error: ReferenceError

// ❌ ผิด - พยายามเรียก Collection โดยตรง
employeeInformation.insertOne({...});

// ✅ ถูกต้อง - ผ่าน db object
db.employeeInformation.insertOne({...});

// ✅ ถูกต้อง - สร้าง Collection ก่อน
db.createCollection("employeeInformation");
db.employeeInformation.insertOne({...});

Auto-Creation (Implicit Creation)

  • MongoDB สร้าง Collection อัตโนมัติเมื่อ Insert Document ครั้งแรก (insertOne, insertMany)
  • ไม่จำเป็นต้อง createCollection() ก่อน Insert
  • แต่ createCollection() จำเป็นหากต้องการตั้งค่า Options: Capped, Size, Validation, Collation, etc.

ตัวเลือก createCollection

db.createCollection("myCollection", {
  capped: true,
  size: 104857600,      // 100MB
  max: 10000,           // Max documents
  validator: {          // Schema Validation
    $jsonSchema: {
      bsonType: "object",
      required: ["name", "email"],
      properties: {
        name: {bsonType: "string"},
        email: {bsonType: "string", pattern: "^.+@.+$"}
      }
    }
  },
  collation: {locale: "th", strength: 2}  // Thai Collation
});