【问题标题】:use match, limit, sort, and lookup together in mongoose query在 mongoose 查询中一起使用匹配、限制、排序和查找
【发布时间】:2020-12-14 02:21:08
【问题描述】:

我有 2 个收藏:

  1. 用户
  2. 通知

用户:

{
  id:1,
  name:ABC
},
{
  id:2,
  name:ABC2
},
{
  id:3,
  name:ABC3
}

通知:

{
  id:1,
  userId:1,
  read:false,
  info: 'Notification for user 1'
},{
  id:2,
  userId:2,
  read:false,
  info: 'Notification for user 2'
},{
  id:3,
  userId:3,
  read:false,
  info: 'Notification for user 3'
}

我想获取具有匹配(读取:false)、排序(createdAt 上的降序)、限制(5)的通知数据,并根据通知数据中的用户 ID 查找用户集合

查询应该返回:

[{
  id:1,
  userId:1,
  read:false,
  info: 'Notification for user 1'
  username:ABC
},{
  id:2,
  userId:2,
  read:false,
  info: 'Notification for user 2'
  username:ABC2
},{
  id:3,
  userId:3,
  read:false,
  info: 'Notification for user 3'
  username:ABC3
}]

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    你可以试试,

    • $match 符合您的条件
    • $lookup加入用户收藏
    • $unwind 解构用户数组,因为它是一个数组,我们需要对象
    • $project 显示必填字段
    • $sort by createdAt 降序排列
    • $limit 5 份文件
    db.notification.aggregate([
      { $match: { read: false } },
      {
        $lookup: {
          from: "user",
          as: "user",
          localField: "userId",
          foreignField: "id"
        }
      },
      { $unwind: "$user" },
      {
        $project: {
          id: 1,
          userId: 1,
          read: 1,
          info: 1,
          username: "$user.name"
        }
      },
      { $sort: { createdAt: -1 } },
      { $limit: 5 }
    ])
    

    Playground

    【讨论】:

    • 感谢@turivishal 抽出宝贵时间。这将在节点中返回“无法在将标头发送到客户端后设置标头”
    • 您需要详细说明您是如何使用和执行查询的。
    • Notification.aggregate([ { $match: { read: false } }, { $lookup: { from: "users", as: "user", localField: "clientId", foreignField: " id" } }, { $unwind: "$user" }, { $project: { id: 1, clientId: 1, read: 1, username: "$user" } }, { $sort: { createdAt: -1 } }, { $limit: 5 } ]).then(....)
    • 我希望这能让问题更清楚@turivishal
    • 不,请显示您是如何打印记录的,它在哪里返回错误,我认为您必须查看 mongoose mongoosejs.com/docs/api/aggregate.html#aggregate_Aggregate 中的文档
    猜你喜欢
    • 2020-04-23
    • 2015-12-20
    • 2014-03-21
    • 2019-05-06
    • 2012-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-03
    相关资源
    最近更新 更多