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

รันฟังก์ชันที่เก็บไว้ (Stored Function) ใน MongoDB

MongoDB อนุญาตให้เก็บ JavaScript Function ไว้ใน System Collection system.js แล้วเรียกใช้ด้วย db.eval() (Deprecated ในเวอร์ชันใหม่)

บันทึกฟังก์ชัน

> db.system.js.save({
    _id: "displayMessage",
    value: function (data) {
        return 'The Name is: ' + data;
    }
})
WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : "displayMessage" })

เรียกใช้ฟังก์ชัน

> db.eval("displayMessage('John')")
WARNING: db.eval is deprecated

ผลลัพธ์

The Name is: John

ข้อควรระวัง:

  • db.eval() ถูก Deprecated แล้ว (MongoDB 4.4+) เนื่องจากล็อคฐานข้อมูลและมีปัญหาด้านความปลอดภัย
  • แนะนำให้ประมวลผลฝั่ง Application (Node.js, Python ฯลฯ) แทน
  • หรือใช้ Atlas Functions / Triggers สำหรับ MongoDB Atlas