【问题标题】:find all documents where it matches a query and the query is a value inside a reference field?查找与查询匹配的所有文档,并且查询是参考字段中的值?
【发布时间】:2021-11-18 19:38:50
【问题描述】:

我试图将我的 Orders 架构中的所有数据与 Orders 架构中的接收者/发送者/driver.phoneNumber 字段之一匹配,我的 Orders 架构将这些字段作为对用户架构的引用,我的问题是当我搜索 phoneNumber 我希望它是正则表达式,这意味着它将返回一个文档数组,所以它不是一个值以便我在订单文档中查询它,我的代码是

else if (searchQuery) {
if (searchQuery.startsWith("07")) {
  const num = "+964" + searchQuery.substring(1);
  const users = await Register.find({            //this will return all users whom phoneNumber start with the query number
    phoneNumber: { $regex: num },
  });
  orders = await Orders.find({
    $or: [
      { receiverId: users },         //this query is obviously wrong, but im trying to implement something like this, 
      { driverId: users },
      { senderId: users },
    ],

    ...branches,
  })
    .limit(limit)
    .skip(skip)

    .populate("receiverId")
    .populate("driverId")
     .populate("senderId")

如何返回与可能用户数组匹配的所有订单文档? 谢谢,

【问题讨论】:

  • 你能显示从RegisterOrders 集合返回的数据格式吗?
  • 订单:receiverId: { type: mongoose.Schema.Types.ObjectId, ref: "Register", }, driverId: { type: mongoose.Schema.Types.ObjectId, ref: "Register", }, senderId: { type: mongoose.Schema.Types.ObjectId, ref: "Register", },
  • fullName: { type: String, }, phoneNumber: { type: String, required: [true, "电话号码必填"], unique: [true, "这个电话号码以前用过"], },
  • 顺便发布了相关字段,@TalESid

标签: node.js mongodb express mongoose


【解决方案1】:

我从您的问题和 cmets 中了解到,您需要 取出匹配 phoneNumber 正则表达式的用户,然后从 Order 架构,获取具有receiverIddriverId 的所有订单 或 senderId 在这些用户数组中。

为了实现这一点,我们首先将用户(仅_ids)作为数组获取。

const user_ids = await Register
.find({ phoneNumber: { $regex: num } })
.distinct('_id');
// This will return only distinct "_id" of users as an array (not an array of objects)

现在,使用这些 id 过滤掉订单

const orders = await Order
.find({
    // the following code means orders where either receiver/driver/sender's id is "IN" the user_ids array, fetched above
    $or: [
        {receiverId: {$in: user_ids}},
        {driverId: {$in: user_ids}},
        {senderId: {$in: user_ids}}
    ],

    ...branches
})

.populate("receiverId")
.populate("driverId")
.populate("senderId")

.limit(limit)
.skip(skip);

这是您的查询(根据我的理解?)

【讨论】:

  • 谢谢我想要的,我只是对 num 变量有一点问题我确实添加了一个“+964”国家代码作为前缀,它不会执行你找到的那一行user_ids,原来是字符串中的 + 号,有点奇怪,但没关系,现在一切正常,哈哈 :)
  • 这是因为正则表达式。 “加号”是正则表达式中的特殊字符,因此您需要像 \+ 一样对其进行转义。您的 num 应以 '\+964' 开头以匹配正则表达式。看到这个->stackoverflow.com/a/2021067/7109362
猜你喜欢
  • 1970-01-01
  • 2020-06-01
  • 2021-12-27
  • 2019-05-06
  • 1970-01-01
  • 1970-01-01
  • 2019-07-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多