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

กำหนด Aliases (นามแฝง) ใน MongoDB Shell ด้วย Object.defineProperty

MongoDB Shell (JavaScript REPL) รองรับการสร้าง Aliases/Shortcuts ผ่าน Object.defineProperty() บน Global Object (this) เพื่อเข้าถึง Function หรือ Value ได้สะดวก

ไวยากรณ์

Object.defineProperty(this, 'yourFunctionName', {
  get: function() {
    // statements
    return value;
  },
  enumerable: true,
  configurable: true
});

// กำหนด Alias ด้วย var
var anyAliasName = yourFunctionName;

ตัวอย่าง: สร้าง Function แสดงข้อความ แล้วตั้ง Alias

> Object.defineProperty(this, 'displayMessageDemo', {
  get: function() {
    return "Hello MongoDB";
  },
  enumerable: true,
  configurable: true
});

กำหนด Alias

> var myMessage = displayMessageDemo;

ใช้งาน Alias

> myMessage;
"Hello MongoDB"

รายละเอียด Property Descriptor

ตัวอย่างใช้งานจริง: Shortcut สำหรับ Query บ่อย


ข้อควรระวัง

  • Alias เก็บอยู่ใน Shell Session เท่านั้น (หายเมื่อปิด Shell)
  • ไม่ใช่ Feature ของ MongoDB Server
  • ใน .mongorc.js 可定義永久别名
  • ไม่ควร Override Built-in Names (db, print, etc.)

.mongorc.js สำหรับ Persistent Aliases

// ~/.mongorc.js
Object.defineProperty(this, 'myColl', {
  get: function() { return db.getSiblingDB('myDB').myCollection; },
  enumerable: true, configurable: true
});

// ใช้งานใน Shell ใหม่ทุกครั้ง
myColl.find().pretty();
Propertyค่าความหมาย
getFunctionGetter Function เรียกเมื่อ Access Property
enumerabletrueแสดงใน for...in loop และ Object.keys()
configurabletrueลบ/แก้ไข Property ได้ (delete, defineProperty อีกครั้ง)
setFunction (Optional)Setter Function เรียกเมื่อ Assign ค่า