0

我无法解决如何实现以下内容:

我有一个像这样的 MongoDB 模式:

var DocumentSchema = new Schema({
  num: Number,
  authors: [String]
})

用于 Backbone 集合的后端。我无法理解如何过滤每个文档的authors数组以匹配用户名。

就像是:

var DocumentCollection = Backbone.Collection.extend({
  model: Document,

  match_username: function() {
    var username = 'foo'
    // match username to author...
    })
  }
});

总而言之,我将对authors集合中每个文档的数组进行过滤,以检查是否存在用户名匹配。如果用户名匹配,则获取num并存储在要返回的新数组中。

解决这个问题的最有效方法是什么?

4

1 回答 1

1

如果我理解正确,听起来您需要的是:

var DocumentCollection = Backbone.Collection.extend({
    model: Document,

    match_username: function() {
        var username = 'foo'
        return this.chain().filter(function(doc) {
            return _.indexOf(doc.get('authors'), username) > -1;
        }).map(function(doc) {
            return doc.get('num');
        }).value();
    }
});

它在 上过滤_.indexOfauthors然后_.mapnum过滤后的集合上。

小提琴

于 2013-08-06T19:39:37.057 回答