MongoDB cho phép lưu hàm JavaScript trong collection hệ thống system.js để tái sử dụng. Sử dụng db.system.js.save() để lưu và db.eval() để thực thi (lưu ý: db.eval đã deprecated).
Lưu hàm displayMessage:
> db.system.js.save({
_id: "displayMessage",
value: function (data) {
return 'The Name is: ' + data;
}
})
Kết quả:
WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : "displayMessage" })
Thực thi hàm:
> db.eval("displayMessage('John')")
WARNING: db.eval is deprecated
Kết quả:
The Name is: John
⚠️ Quan trọng:
db.eval()đã **deprecated** từ MongoDB 3.0 và **removed** từ 4.4. Không dùng trong production.system.jscollection lưu hàm toàn cục (global) cho database.- Hàm lưu trữ chạy trên server (server-side JavaScript - SpiderMonkey).
Thay thế hiện đại:
- Xử lý logic ở application layer (driver/client)
- Dùng
$functiontrong aggregation (MongoDB 4.4+) cho logic tùy chỉnh server-side - Dùng Atlas Functions / Realm Functions cho serverless functions