不带参数的 CouchDB Emit

CouchDB Emit with no parameters

考虑以下代码:

module.exports = {
  by_author: {
    map: function(doc) {
      if ('authors' in doc) {
        doc.authors.forEach(emit);
      }
    }.toString(),
    reduce: '_count'
  },

  by_subject: {
    map: function(doc) {
      if ('subjects' in doc) {
        doc.subjects.forEach(function(subject){
          emit(subject, subject);

          subject.split(/\s+--\s+/).forEach(function(part){
            emit(part, subject);
          });
        });
      }
    }.toString(),

    reduce: '_count'
  }
};

看起来 doc.authors.forEach(emit); 不是有效的语法(或良好的编码),但它在语法上似乎是正确的。

我的问题是,这个 shorthand 用于以下内容:

doc.authors.forEach(function(_doc) {
    emit(_doc.id, _doc);
});

如果是这样,使用这个 shorthand 有什么好处吗?它是如何工作的?

参考。 https://wiki.apache.org/couchdb/Introduction_to_CouchDB_views#Map_Functions

emit 是 CouchDB 公开的一个函数。在 JS 中函数是 first-class。 (并且可以作为参数传递给其他函数)

为了代替解释所有这些,我将只向您展示您的代码实际在做什么。 (如果您是新手,请阅读更多关于 JS 中的函数的信息)

doc.authors.forEach(emit);

doc.authors.forEach(function (item, index, list) {
  emit(author, index, list);
});

在 JS 中,传递给 forEach 处理程序 fn 的参数是:

  • 数组中的项目(即:"some user"
  • 该项目在数组中的索引(例如:0
  • 整个数组(例如:[ "some user" ]

emit() 函数只接受 2 个参数,所以第 3 个参数将被忽略。因此,在单项数组的情况下,您将得到 emit("some user", 0) 的等价物。如果有多个项目,你也会得到其他发射。