I am trying to create function in MongoDB and then call it. I am unable to do so.
I tried 2 ways
- db.Test.save({
_id: “displayMessage”,
value: function (data) {
return 'The Name is: ’ + data;
}
})
This method, I call like
db.eval(“displayMessage(‘John’)”);
but no success. I come to know that eval is not supported anymore. I would Like to know that how to call it now!
- I created this function in ROBO3T
When I pass value, this happens.

I want to understand how to understand and Implement functions in MongoDB. Can’t find any implementation or understanding so far.
alexbevi
(Alex Bevilacqua)
2
Hi @MWD_Wajih_N_A,
See the documentation for Store a JavaScript Function on the Server to see how a function can be stored.
To use these functions in the mongo shell they will have to be loaded via a call to db.loadServerScripts() first.
For example:
db.system.js.insertOne(
{
_id: "echoFunction",
value : function(x) { return x; }
}
);
db.loadServerScripts();
echoFunction("test")
Note that these server-side JavaScript functions are not the same thing as MongoDB Realm Functions.
1 Like
Hi @alexbevi,
I am getting db.loadServerScripts() is not a function from mongoshell while running from mongoshell and atlas’s shell, how can i solve this issue ?
Mongoshell version: 1.1.7
Mongo atlas version: 1.28.4
Appreciate any help.
Hello.
I’m having exactly the same issue when using MongoDB Shell, this is not a problem if I use the “Legacy” shell from Mongo 4.2; I suspect the problem is that db.loadServerScripts() is not yet supported on MongoDB Shell or at least that method is not listed at https://www.mongodb.com/docs/mongodb-shell/reference/methods/ yet.
Does anyone know if there a workaround for this other than loading the custom functions from a JS file?
1 Like
Hi @Jeffrey_G, you are correct that db.loadServerScripts() is a method from the legacy shell. Additionally starting in MongoDB 8.0 server-side JavasScript is deprecated.
The linked page https://www.mongodb.com/docs/upcoming/tutorial/store-javascript-function-on-server/ has been updated to reflect this and offer a alternative solution for mongosh, which is detailed on the https://www.mongodb.com/docs/mongodb-shell/write-scripts/#std-label-mdb-shell-write-scripts. I hope this helps clear up some of the confusion!