Home > other >  find all documents where it matches a query and the query is a value inside a reference field?
find all documents where it matches a query and the query is a value inside a reference field?

Time:09-26

im trying to ruturn all the data in my Orders schema where it matches one of the receiver/sender/driver.phoneNumber field in Orders schema, my Orders schema has those fields as a refernce to Users schema, my issue is when I search for a phoneNumber I want it to be regex, so that means it will return an array of documents, so its not a single value in order for me to query it inside the order document, my code is

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")

how to return all the order documents where it matches the array of possible users? thanks,

CodePudding user response:

What I understand from your question and comments is that you need to fetch out users with matching phoneNumber regex and then from Order schema, get all orders having either receiverId, driverId or senderId in those users array.

To achieve this, let's first fetch users (only _ids) as an array.

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)

Now, filter out orders using these ids

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);

Here is your query (according to my understanding

  • Related