【问题标题】:Mongodb Aggregation returning nothing when trying to do $lookup and $unwind尝试执行 $lookup 和 $unwind 时,Mongodb 聚合不返回任何内容
【发布时间】:2022-01-25 13:14:04
【问题描述】:

我正在尝试根据chatroomId 获取消息并返回该聊天室中的所有消息,并从userId 添加有关用户的所有数据。我尝试了以下方法,但它返回一个空数组。

我做错了什么?

chatMessageSchema.statics.getConversationByRoomId = async function (
  chatRoomId,
  options = {}
) {
  try {
    return this.aggregate([
      { $match: { chatRoomId } },
      { $sort: { createdAt: -1 } },

      {
        $lookup: {
          from: "User",
          localField: "userId",
          foreignField: "_id",
          as: "user",
        },
      },
      { $unwind: "$user" },

      { $skip: options.page * options.limit },
      { $limit: options.limit },
      { $sort: { createdAt: 1 } },
    ]);
  } catch (error) {
    throw error;
  }
};

【问题讨论】:

    标签: node.js database mongodb rest express


    【解决方案1】:

    { $match: { chatRoomId } } => { $match: { _id:chatRoomId } }

    db.chatMessages.aggregate([
      {
        $match: { _id: 1 }
      },
      {
        $sort: { createdAt: -1 }
      },
      {
        $lookup: {
          from: "User",
          localField: "userId",
          foreignField: "_id",
          as: "user"
        }
      },
      {
        $unwind: "$user"
      },
      {
        $skip: 0
      },
      {
        $limit: 1
      },
      {
        $sort: { createdAt: 1 }
      }
    ])
    

    mongoplayground

    【讨论】:

    • 我试过了,还是不行。 js { $match: { _id: chatRoomId } }, { $sort: { createdAt: -1 } }, { $lookup: { from: "User", localField: "userId", foreignField: "_id", as: "user", }, }, { $unwind: "$user" }, { $skip: options.page * options.limit }, { $limit: options.limit }, { $sort: { createdAt: 1 } },
    • 我也尝试了id:,但情况变得更糟。因为当我删除查找并倒带时它可以工作,但是当我添加 id: 它停止工作(返回空数组)。
    • @ssaqan 在我的mongoplayground 中它起作用了。您最好检查每个聚合级别和所有输入参数。
    猜你喜欢
    • 2019-09-03
    • 2021-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-19
    • 2021-11-09
    相关资源
    最近更新 更多