Syntax error How to work with Stored JavaScript in MongoDB?

How to work with Stored JavaScript in MongoDB?



It is saved in the special system.js collection. For this, use db.system.js.save(). Following is the syntax −

db.system.js.save({
   _id: "anyFunctionName",
   value: function (returnValue) {
      return ‘yourMessage ' + returnValue;
   }
})

Let us implement the above syntax. Following is the query −

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

Following is the query to call the above function to print the actual data −

> db.eval("returnValue(20)")
WARNING: db.eval is deprecated

This will produce the following output −

The value==== 20
Updated on: 2020-05-13T09:40:09+05:30

462 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements