Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB. How to execute stored function in node.js?

How can I execute stored function from mongodb. I found solution with db.eval(), but it suitable for me.

For example i have document like this:

{
  email: '[email protected]',
  mobile: +38000000,
  user: function(user) {
    return user.lastName + ' ' + user.firstName
  },
}

Can I somehow execute this function in node.js? I've tried to get this field and pass it to new Function constructor, it didn't work, also tried to use eval() with it, and also nothing happened. Maybe there is another way? Would be appreciate for any advise

like image 463
Alex Bryanskiy Avatar asked Aug 05 '26 23:08

Alex Bryanskiy


1 Answers

What you can do is this:

First store your function as a string. like this:

{
  email: '[email protected]',
  mobile: +38000000,
  user: 'function(user) {return user.lastName + " " + user.firstName}' // Save it as string
}

Or if you have this function in code somewhere (named function not anonymouse) you can do this:

{
  email: '[email protected]',
  mobile: +38000000,
  user: myCoolFunction.toString()  // Note here the toString call
}

Then when you fetch this record from mongo db, eval the user property like this:

eval("let funcToExec = " + dbRecord.user); // Note that this restores your function back into any variable you want which you can use later in code
// Then execute your function simply like this:
funcToExec({firstName: "Michael", lastName: "Jacksonn"});

Let me know if that worked for you!

like image 101
Mercury Avatar answered Aug 08 '26 13:08

Mercury



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!