2015-10-09 37 views
0

我目前使用下面的代码来筛选两个单独的集合。一个集合包含发送给用户的消息的总列表。第二个集合包含来自用户的所有回复。Mongoose Aggregate Field结果数组

从第一个集合开始,我构建了一个发送的消息数组 - 然后查询第二个集合以搜索在该数组中没有匹配的所有响应。

两个问题:

1)是否有输出猫鼬/ MongoDB的更好的办法产生到一个数组比我现在用的for循环的方法呢?

2)有没有更好的方法来比较这些集合比我使用?

// Find all responses (read) messages associated with a patient. 
Response.find({patientID: patientID}, function(err, responses){ 

    // Store all msgIDs into an array. 
    for (var i = 0; i < responses.length; i++){ 
     openedArray.push(responses[i].msgID); 
    } 

    // Find all messages associated with that same patient, but that were not included in the response list 
    Message.find({patientList: patientID, msgID: { $ne: openedArray}}, function(err, unopenedMessages){ 

     // Store all msgIDs into an array. 
     for (var j = 0; j < unopenedMessages.length; j++){ 
      unopenedArray.push(unopenedMessages[j].msgID); 
     } 

     // Output a list of unopened messages (msgIDs) and a count of total unread messages 
     res.json({unread: unopenedArray, count: unopenedArray.length}) 
    }); 
}); 

回答

1

您可以使用.distinct()以及对async.waterfall也许一些使用清理嵌套一点:

async.waterfall(
    [ 
     function(callback) { 
      Response.distinct("msgID",{ "patientID": patientID },callback); 
     }, 
     function(opened,callback) { 
      Message.distinct(
       "msgID", 
       { 
        "patientList": patientID, 
        "msgID": { "$nin": opened } 
       }, 
       callback 
      ); 
     } 
    ], 
    function(err,unopened) { 
     // maybe handle error 
     res.json({ "unopened": unopened, "count": unopened.length }); 
    } 
); 

你也可能要$nin对列表进行比较返回反对第二集合中的字段。

waterfall将每个异步调用的结果传递到下一个阶段,这意味着您不需要将每个调用嵌套在另一个调用中,因此看起来更清晰。

+0

感谢这个async.waterfall是一个很好的技巧以及独特的技巧。欣赏它! –