过滤器如何在Mongoose中工作?

时间:2018-01-15 20:38:23

标签: javascript mongoose

我见过一个在mongoose schema中执行过滤器的教程

我想知道这是如何运作的。

 const isConversationExist = user.conversations.filter(conversation => (
         conversation.userOneId === request.payload.friendId || conversation.userTwoId === request.payload.friendId)
        ,).length > 0)

1 个答案:

答案 0 :(得分:1)

将其分解为以

开头的碎片
  

user.conversations.filter(A)

filter()方法创建一个新数组,其中包含通过所提供函数(A)实现的测试的所有元素。

在代码中,提供的函数(A)使用ES6 arrow notation

编写
conversation => (
    conversation.userOneId === request.payload.friendId || conversation.userTwoId === request.payload.friendId
)

可以重写(但不总是)

function (conversation) {
    return conversation.userOneId === request.payload.friendId || conversation.userTwoId === request.payload.friendId;
}

它基本上表示,对于每个元素即会话,测试对话的用户ID是否等于request.payload.friendId

如果测试通过(如函数返回true),则元素将被添加到新数组中;否则,该元素将被忽略。

  

user.conversations.filter(A)。长度

这将是新数组的大小,所有会话通过测试。

  

user.conversations.filter(A).length> 0

这是一个布尔值,无论新数组是否有通过测试的对话,即isConversationExist