我有一个带有对象字段数组的mongoDB文档,如下所示:

"leaving_users" : [
        {
            "user_id" : "FZ78Pr82JPz66Gc3p",
            "leaving_date" : ISODate("2015-06-12T14:14:14.501Z")
        }
    ]


我可以使用_.pluck获取与特定leaving_date相关的user_id吗?

我的代码似乎可以正常工作,但是我想检查一下这是否是正确的方法,并且如果使用_.pluck函数,请确保有时不会以其他索引结尾。

这是我的代码:

if (doc.leaving_users //guarding
    //if the user belongs to the leaving_users object array
    &&  _.pluck(doc.leaving_users, "user_id").indexOf(userId) != -1
    //if his leaving_date field is after yesterday
    && doc.leaving_users[_.pluck(doc.leaving_users, "user_id").indexOf(userId)].leaving_date > yesterday)
                {
                    leftRecently  = true;
                }   else{
                    leftRecently  = false;
                }


额外的问题:您将如何使其更加优雅?

最佳答案

是的,索引将相同。如果查看the implementation of _.pluck,这很明显:

_.pluck = function(obj, key) {
  return _.map(obj, _.property(key));
};


...和the implementation of _.map

_.map = _.collect = function(obj, iteratee, context) {
  iteratee = cb(iteratee, context);
  var keys = !isArrayLike(obj) && _.keys(obj),
      length = (keys || obj).length,
      results = Array(length);
  for (var index = 0; index < length; index++) {
    var currentKey = keys ? keys[index] : index;
    results[index] = iteratee(obj[currentKey], currentKey, obj);
  }
  return results;
};




就是说,我不会像这样两次调用_.pluck,并且我认为我根本不会使用_.pluck,我会使用_.findIndex并保存结果:

var index;
if (doc.leaving_users //guarding
    //if the user belongs to the leaving_users object array
    && (index = _.findIndex(doc.leaving_users, function(e) { e.user_id === userId; }) !== -1)
    //if his leaving_date field is after yesterday
    && doc.leaving_users[index].leaving_date > yesterday)
                {
                    leftRecently  = true;
                }   else{
                    leftRecently  = false;
                }

10-01 01:02