Functions Implementation and Understanding

I am trying to create function in MongoDB and then call it. I am unable to do so.
I tried 2 ways

  1. 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!

  1. I created this function in ROBO3T
    image

When I pass value, this happens.
image

I want to understand how to understand and Implement functions in MongoDB. Can’t find any implementation or understanding so far.

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