Reputation: 435
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
Upvotes: 3
Views: 1465
Reputation: 7988
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!
Upvotes: 1