猫鼬聚合未返回最新文档

时间:2020-01-08 17:38:11

标签: node.js mongodb mongoose aggregation-framework

我有一个返回文档的聚合,但是我需要它来返回文档messageTrackingId中最新的文档。在creationDate字段中具有最新值的文档可以完成此操作,但是我不断收到返回的文档不是最新的文档,我不确定为什么。目的是向用户显示该用户与另一个用户之间发送的最后一条消息的时间戳,而不管是谁发送的。感谢您的帮助。

app.get("/api/messages", (req, res, next) => {
  query = {};
  inbox = false;
  messageId = false;
  console.log(req.query.recipientId);
  if (req.query.recipientId) {
    query = { recipientId: req.query.recipientId };
    inbox = true;

    Messages.aggregate([
      {
        $match: {
          $or: [
            { recipientId: req.query.recipientId },
            { creator: mongoose.Types.ObjectId(req.query.recipientId) }
          ]
        }
      },
      {
        $addFields: {
          conversant: {
            $cond: [
              { $ne: ["$recipientId", req.query.recipientId] },
              "$recipientId",
              "$creator"
            ]
          }
        }
      },
      {
        $sort: { creationDate: 1 }
      },
      {
        $group: {
          _id: "$conversant",
          message: { $last: "$message" },
          recipientId: { $last: "$recipientId" },
          creator: { $last: "$creator" },
          messageTrackingId: { $last: "$messageTrackingId" },
          recipient: { $last: "$recipient" },
          creationDate: { $last: "$creationDate" }
        }
      },
      {
        $lookup: {
          from: "users",
          let: { creator: "$creator" },
          pipeline: [
            { $match: { $expr: { $eq: ["$_id", "$$creator"] } } },
            { $project: { instagramName: 1 } }
          ],
          as: "creatorName"
        }
      }
    ]).then(documents => {


      if (inbox === true) {
        res.status(200).json({
          message: "User's Inbox Retrieved!",
          posts: documents
        });
      }

    });

我清除了消息表,并来回发送了3条消息进行演示。重新加载页面时,我在JSON响应中仅收到其中两个文档,而不是最新的。在收到的两个中,似乎都不是最新的。我不确定为什么不返回一个。请在下面查看页面加载时的输出。

消息:

/* 1 */
{
    "_id" : "5e16463be5fcba1d2c56ebb7",
    "creator" : "5e0a1d41f86e1e4234fc1a77",
    "recipient" : "andy",
    "recipientId" : "5df0014e25ee451beccf588a",
    "message" : "First message",
    "messageTrackingId" : "17c4fc99-d92f-46ef-9bae-1408f415287a",
    "creatorName" : "buyer1",
    "creationDate" : ISODate("2020-01-08T21:14:35.104Z"),
    "__v" : 0.0
}

/* 2 */
{
    "_id" : "5e16464de5fcba1d2c56ebb9",
    "creator" : "5df0014e25ee451beccf588a",
    "recipient" : "buyer1",
    "recipientId" : "5e0a1d41f86e1e4234fc1a77",
    "message" : "Second Message",
    "messageTrackingId" : "17c4fc99-d92f-46ef-9bae-1408f415287a",
    "creatorName" : "andy",
    "creationDate" : ISODate("2020-01-08T21:14:53.618Z"),
    "__v" : 0.0
}

/* 3 */
{
    "_id" : "5e16465ce5fcba1d2c56ebbb",
    "creator" : "5e0a1d41f86e1e4234fc1a77",
    "recipient" : "andy",
    "recipientId" : "5df0014e25ee451beccf588a",
    "message" : "Third Message",
    "messageTrackingId" : "17c4fc99-d92f-46ef-9bae-1408f415287a",
    "creatorName" : "buyer1",
    "creationDate" : ISODate("2020-01-08T21:15:08.500Z"),
    "__v" : 0.0
}

用户:

/* 1 */
{
    "_id" : "5df00d08c713f722909c99c1",
    "email" : "joe@gmail.com",
    "password" : "$2b$10$5eWhwL4RNT8TyQRCC191J.myYBwFcJ8hCARqGfofYWUmRaq6jJFQm",
    "instagramName" : "joe",
    "over21" : "Yes",
    "role" : "Artist",
    "fullName" : "testdsfdfsfs",
    "address1" : "adfsdf",
    "address2" : "dssdf",
    "city" : "sdfsdfsdf",
    "state" : "dsffsdsd",
    "zip" : "dsdfsdf",
    "passwordCreated" : ISODate("2020-01-07T23:46:57.861Z"),
    "__v" : 0
}

/* 2 */
{
    "_id" : "5df0014e25ee451beccf588a",
    "email" : "andy@gmail.com",
    "password" : "$2b$10$fNHmIoDb4mX6x.YeMLXHbu2yIaeW6HVQvNpZR8Nt/a4xVFkhxM1Ey",
    "instagramName" : "andy",
    "over21" : "Yes",
    "role" : "Artist",
    "fullName" : "dsfdsfdfdsf",
    "address1" : "111",
    "address2" : "111",
    "city" : "atlanta",
    "state" : "ga",
    "zip" : "33222",
    "passwordCreated" : ISODate("2019-12-19T15:29:46.528Z"),
    "__v" : 0
}

必需的输出(返回每个用户的最后一条消息):

/* 1 */
{
    "_id" : {
        "conversant" : "5df0014e25ee451beccf588a",
        "recipient" : "andy"
    },
    "message" : "Third Message",
    "recipientId" : "5df0014e25ee451beccf588a",
    "creator" : "5e0a1d41f86e1e4234fc1a77",
    "messageTrackingId" : "17c4fc99-d92f-46ef-9bae-1408f415287a",
    "recipient" : "andy",
    "creationDate" : ISODate("2020-01-08T21:15:08.500Z"),
    "creatorName" : [ 
        {
            "_id" : "5df0014e25ee451beccf588a",
            "instagramName" : "andy"
        }
    ]
}

/* 2 */
{
    "_id" : {
        "conversant" : "5df0014e25ee451beccf588a",
        "recipient" : "buyer1"
    },
    "message" : "Second Message",
    "recipientId" : "5e0a1d41f86e1e4234fc1a77",
    "creator" : "5df0014e25ee451beccf588a",
    "messageTrackingId" : "17c4fc99-d92f-46ef-9bae-1408f415287a",
    "recipient" : "buyer1",
    "creationDate" : ISODate("2020-01-08T21:14:53.618Z"),
    "creatorName" : [ 
        {
            "_id" : "5df0014e25ee451beccf588a",
            "instagramName" : "andy"
        }
    ]
}

1 个答案:

答案 0 :(得分:1)

更改必须为

1)如果我现在正确理解,您想在一个字段上按recipientId分组(因为您不能在两个字段上分组一个值),因此您正在创建一个名为{ {1}},因此必须为conversant,或者您需要交换$eqrecipientId,也必须为creator

$toString

2)您不需要这个{ $addFields: { conversant: { $cond: [ { $eq: ["$recipientId", req.query.recipientId] }, "$recipientId", {$toString : "$creator"} ] } } } 阶段,因为所有最新添加的集合都会在末尾添加(期望$sort一旦创建但从未更新):

creationDate

此外,您需要按// Not useful { $sort: { creationDate: 1 } } 分组,以便根据_id: { conversant: "$conversant", recipient: '$recipient' }对最近的邮件进行分组。在user中更改为此$lookup

尝试一下:

let: { conversant: "$_id.conversant" }