How to use scope variables as property names in a Mongo Map/Reduce emit

不想你离开。 提交于 2019-12-12 01:17:35

问题


There is a question (and answer) that deals with the general case. I am having difficulty using a scope variable as a field key (as opposed to the field value)

In the example below all the FULLY_CAPS fields are scope variables. In the case of SERVICE and IDENTIFIER the emit correctly uses the value of the scope variable as it is passed to the M/R.

However when I try to use the value of a scope variable as a key in the emitted document, the document is created with the scope variable name (as opposed to it's value).

return emit({
    service: SERVICE,
    date: _this.value.date,
    identifier: _this.value[IDENTIFIER]
  }, {
    errors: {
      count: 1,
      type_breakdown: {
        SINGLES_ONLY: {
          count: 1
        }
      }
    }
  });

Is there a way around this problem?


回答1:


When using the shortcut syntax for creating objects in JavaScript, the left hand side/property name is always interpreted as a literal value, regardless of quotes.

For example:

var d={ name: "Aaron" }

Is equivalent to:

var d={ "name" : "Aaron" }

As there are two ways to set a property value:

  1. obj.propertyName=value
  2. obj["propertName"]=value

You have to construct your object using the second syntax, at least in part.

var errors={
      count: 1,
      type_breakdown: { }
      }
    };
var countObj={ count:1 };
errors.type_breakdown[SINGLES_ONLY]=countObj;

// pass results to emit call


来源:https://stackoverflow.com/questions/18441723/how-to-use-scope-variables-as-property-names-in-a-mongo-map-reduce-emit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!