3

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

4
  • Hi what were the error messages when it didn't work? Commented Nov 15, 2018 at 8:30
  • It was no error, it just returned undefined. I wrote for example purposes function like this function () { return 0;}. But like i said i get undefined; Commented Nov 15, 2018 at 8:33
  • Could you add some of the code you tried in your question to see what you've actually tried so far Commented Nov 15, 2018 at 8:48
  • function should not be stored in normal collections it should be stored in system collection and can be used in query refer this link dirolf.com/2010/04/05/… Commented Nov 15, 2018 at 9:20

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.