You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mongoose如何查询关联用户手机号满足正则匹配的全部订单文档

解决方法

你当前的问题是直接把完整的用户文档数组传入了查询条件,而订单关联字段存储的是用户的_id值,只需要先提取符合条件用户的_id数组,再搭配$in操作符匹配三个关联字段即可。

修正后代码

else if (searchQuery) {
  if (searchQuery.startsWith("07")) {
    const num = "+964" + searchQuery.substring(1);
    // 只查询返回用户_id字段,减少无效数据传输、提升性能
    const users = await Register.find(
      { phoneNumber: { $regex: num } },
      { _id: 1 }
    );
    // 提取符合条件的用户_id数组
    const matchUserIdList = users.map(user => user._id);
    orders = await Orders.find({
      $or: [
        { receiverId: { $in: matchUserIdList } },
        { driverId: { $in: matchUserIdList } },
        { senderId: { $in: matchUserIdList } },
      ],
      ...branches,
    })
      .limit(limit)
      .skip(skip)
      .populate("receiverId")
      .populate("driverId")
      .populate("senderId")
  }
}

可选优化方案(单次查询实现)

如果不想分两次请求数据库,也可以直接用MongoDB聚合查询一次性完成关联匹配:

else if (searchQuery) {
  if (searchQuery.startsWith("07")) {
    const num = "+964" + searchQuery.substring(1);
    orders = await Orders.aggregate([
      // 先应用你的branches过滤条件
      { $match: branches },
      // 关联用户表匹配手机号
      {
        $lookup: {
          from: "registers", // 替换为Register模型对应的数据库集合名,通常为小写复数格式
          let: { receiverId: "$receiverId", driverId: "$driverId", senderId: "$senderId" },
          pipeline: [
            {
              $match: {
                $expr: {
                  $or: [
                    { $eq: ["$_id", "$$receiverId"] },
                    { $eq: ["$_id", "$$driverId"] },
                    { $eq: ["$_id", "$$senderId"] }
                  ]
                },
                phoneNumber: { $regex: num }
              }
            }
          ],
          as: "matchedUsers"
        }
      },
      // 过滤出存在匹配用户的订单
      { $match: { "matchedUsers.0": { $exists: true } } },
      // 分页逻辑
      { $skip: skip },
      { $limit: limit },
    ])
    // 聚合结果需要populate关联字段的话,可以调用mongoose的populate方法处理聚合返回值
    .populate("receiverId")
    .populate("driverId")
    .populate("senderId")
  }
}

内容的提问来源于stack exchange,提问作者Lhon Rafaat Mohammed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 03:54:02