# 对 Map Function 进行故障排除

`map` function 是一个 JavaScript function，它将 value 与 key 关联或“maps”，并在[map-reduce](/aggregation/map-reduce/troubleshoot-the-map-function.md)操作期间发出 key 和 value 对。

要验证`map` function 发出的`key`和`value`对，请编写自己的`emit` function。

考虑一个包含以下原型文档的集合`orders`：

```
{
     _id: ObjectId("50a8240b927d5d8b5891743c"),
     cust_id: "abc123",
     ord_date: new Date("Oct 04, 2012"),
     status: 'A',
     price: 250,
     items: [ { sku: "mmm", qty: 5, price: 2.5 },
              { sku: "nnn", qty: 5, price: 2.5 } ]
}
```

* 为每个文档定义\_ma 功能

  ```
  var map = function() {
      emit(this.cust_id, this.price);
  };
  ```
* 定义`emit` function 以打印 key 和 value：

  ```
    var emit = function(key, value) {
        print("emit");
        print("key: " + key + "  value: " + tojson(value));
    }
  ```
* 使用`orders`集合中的单个文档调用`map` function：

  ```
    var myDoc = db.orders.findOne( { _id: ObjectId("50a8240b927d5d8b5891743c") } );
    map.apply(myDoc);
  ```
* 验证 key 和 value 对是否符合预期。

  ```
    emit
    key: abc123 value:250
  ```
* 使用`orders`集合中的多个文档调用`map` function：

  ```
    var myCursor = db.orders.find( { cust_id: "abc123" } );
    while (myCursor.hasNext()) {
        var doc = myCursor.next();
        print ("document _id= " + tojson(doc._id));
        map.apply(doc);
        print();
    }
  ```
* 验证 key 和 value 对是否符合预期。

> **也可以看看**
>
> map`function 必须满足各种要求。有关`map\` function 的所有要求的列表，请参阅[MapReduce](/aggregation/map-reduce/troubleshoot-the-map-function.md)或[mongo](/aggregation/map-reduce/troubleshoot-the-map-function.md) shell 辅助方法[db.collection.mapReduce()](/aggregation/map-reduce/troubleshoot-the-map-function.md)。

译者：李冠飞

校对：


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.mongoing.com/aggregation/map-reduce/troubleshoot-the-map-function.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
