问题
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:
obj.propertyName=value
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