Home > Enterprise >  how to filter collection docs based on another collection?
how to filter collection docs based on another collection?

Time:01-13

I want to create a controller for my mongo collection of cases and users. I want to filter the cases that have a userName prop that does not associate with a user in the Users collection. I want to respond to the client with the caseDocs that have problematic usersNames.

Below is what I've been banging my head with:

const noUserFuncController = async (res, res) => {
  const cases = await CaseFile.find({})
  const noUsersarr = []
   cases.forEach(async caseDoc => {
    const usr = await Users.findOne({ userName: caseDoc.user })
    if (!usr) {
      noUsers.push(caseDoc)
    }
  })
  res.json(noUsersarr)
}

Any input is appreciated.
thank you.

CodePudding user response:

You can try a aggregation query with $lookup stage to join user information, and $match stage to match if user response if empty [],

const noUserFuncController = async (res, res) => {

  const noUsersarr = await CaseFile.aggregate([
    {
      $lookup: {
        from: "users", // confirm your collection name here
        localField: "user",
        foreignField: "userName",
        as: "user"
      }
    },
    { $match: { user: [] } }
  ]);

  res.json(noUsersarr);

}
  •  Tags:  
  • Related