【问题标题】:"Evaluate" Function that is stored in MongoDB Server存储在 MongoDB 服务器中的“评估”函数
【发布时间】:2018-06-23 00:17:38
【问题描述】:

我的收藏是这样的:

> db.projects_columns.find()
{ "_id" : "5b28866a13311e44a82e4b8d", "checkbox" : true }
{ "_id" : "5b28866a13311e44a82e4b8e", "field" : "_id", "title" : "ID", "sortable" : true }
{ "_id" : "5b28866a13311e44a82e4b8f", "field" : "Project", "title" : "Project", "editable" : { "title" : "Project", "placeholder" : "Project" } }
{ "_id" : "5b28866a13311e44a82e4b90", "field" : "Owner", "title" : "Owner", "editable" : { "title" : "Owner", "placeholder" : "Owner" } }
{ "_id" : "5b28866a13311e44a82e4b91", "field" : "Name #1", "title" : "Name #1", "editable" : { "title" : "Name #1", "placeholder" : "Name #1" } }
{ "_id" : "5b28866a13311e44a82e4b92", "field" : "Name #2", "title" : "Name #2", "editable" : { "title" : "Name #2", "placeholder" : "Name #2" } }
{ "_id" : "5b28866a13311e44a82e4b93", "field" : "Status", "title" : "Status", "editable" : { "title" : "Status", "type" : "select", "source" : [ { "value" : "", "text" : "Not Selected" }, { "value" : "Not Started", "text" : "Not Started" }, { "value" : "WIP", "text" : "WIP" }, { "value" : "Completed", "text" : "Completed" } ], "display" : "function (value, sourceData) { var colors     = { 0: 'Gray', 1: '#E67C73', 2: '#F6B86B', 3: '#57BB8A' }; var status_ele = $.grep(sourceData, function(ele){ return ele.value == value; });  $(this).text(status_ele[0].text).css('color', colors[value]); }", "showbuttons" : false } }

您可以在最后一个文档中看到我将函数存储为文本。现在的想法是我将请求此数据并且将采用 Javascript 数组格式。

但我希望能够在没有引号的情况下使用我的功能!您可以看到,简单地评估它是行不通的,因为我需要让它仍然需要在对象内部准备好在使用数组时执行。

我怎样才能做到这一点?

感谢您的帮助!

【问题讨论】:

    标签: javascript node.js mongodb server client


    【解决方案1】:

    有两种可能的解决方案,但都不是特别安全,您应该首先认真考虑为什么需要将函数存储为字符串。话虽如此,你可以做两件事。

    最简单的是使用eval。为此,您必须首先像正常一样解析对象,然后将您想要的属性设置为评估函数字符串的结果,如下所示:

    // Pass in whatever JSON you want to parse
    var myObject = JSON.parse(myJSONString);
    // Converts the string to a function
    myObject.display = eval("(" + myObject.display + ")");
    // Call the function with whatever parameters you want
    myObject.display(param1, param2);
    

    额外的括号是为了确保评估正常进行。请注意,Mozilla 认为这是不安全的,并且明确建议不要使用 eval。

    第二个选项是使用Function 构造函数。为此,您需要重组数据以便单独存储参数,这样您就可以执行以下操作:

    var myObject = JSON.parse(myJSONString);
    // displayParam1 and displayParam2 are the stored names of your parameters for the function
    myObject.display = Function(myObject.displayParam1, myObject.displayParam2, myObject.display)
    

    这种方法肯定需要更多的修改,所以如果你想使用你现有的结构,我推荐eval。但是,再次确保这是绝对必要的,因为两者都被认为是不安全的,因为外部参与者基本上可以将代码注入您的服务器。

    【讨论】:

    • 谢谢,括号的缺失实际上是造成我的问题的原因。但如果你能告诉我,我需要评估函数的原因是我创建了一个表,你可能会猜到它在一个对象参数中使用了一个函数。我想将它存储在服务器端,以便客户端可以创建该功能的多个版本。如果有任何方法可以让这个更安全/更简单,请告诉我!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-29
    • 2013-03-17
    相关资源
    最近更新 更多