我有一个mongoDB文档,其中包含一个对象数组字段,如下所示:
"leaving_users" : [
{
"user_id" : "FZ78Pr82JPz66Gc3p",
"leaving_date" : ISODate("2015-06-12T14:14:14.501Z")
}
]
我可以使用_.pluck
获取与特定leaving_date
相关的user_id
吗?
我的代码似乎工作正常但我想检查这是正确的方法,并确保如果我使用_.pluck
函数,我有时不会使用不同的索引。< / p>
这是我的代码:
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;
}
奖金问题:你怎么能让它更优雅?
答案 0 :(得分:2)
是的,索引将是相同的。如果你看一下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
使用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;
}
。 d使用_.findIndex
并保存结果:
script