MongoDB。如何在node.js中执行存储函数?

3

如何从mongodb中执行存储函数。我发现使用db.eval()的解决方案,但它不适合我。

例如我有一个像这样的文档:

{
  email: 'test@gmail.com',
  mobile: +38000000,
  user: function(user) {
    return user.lastName + ' ' + user.firstName
  },
}

我能在 node.js 中执行这个函数吗?我试过获取该字段并将它传递给新的 Function 构造函数,但是没有成功。我也尝试使用 eval(),但是仍然没有任何反应。也许还有其他方法?非常感谢任何建议。


嗨,当它没有工作时,有什么错误信息? - t3__rry
这不是错误,它只是返回未定义。我为了举例编写了一个函数,像这样:function () { return 0;}。但正如我所说,我得到了未定义的结果。 - Alex Bryanskiy
你能否在你的问题中添加一些你尝试过的代码,以便了解你目前所尝试的内容? - t3__rry
函数不应存储在普通集合中,而应存储在“system”集合中,并可在查询中使用。请参考此链接:http://dirolf.com/2010/04/05/stored-javascript-in-mongodb-and-pymongo.html - Aabid
1个回答

1
你可以这样做:
首先将你的函数存储为字符串,像这样:
{
  email: 'test@gmail.com',
  mobile: +38000000,
  user: 'function(user) {return user.lastName + " " + user.firstName}' // Save it as string
}

或者,如果您的代码中已经有此函数(命名函数而非匿名函数),则可以执行以下操作:

{
  email: 'test@gmail.com',
  mobile: +38000000,
  user: myCoolFunction.toString()  // Note here the toString call
}

然后当你从MongoDB中获取该记录时,可以像这样评估用户属性:

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"});

如果这对您有用,请告诉我!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接