Search code examples
reactjsmongodbfindurlsearchparams

MongoDB find an array that contains one of the elements from another array



I'm doing a school project and I'm stuck :(
When the url is ".../?liked=true" I want to show only likedInterns.
likedInterns is an array with IDs = ['628f8f1f7a7a944bd8927c1b', '6291241d80feece846cbc104', '628f8f1f7a7a944bd8927c1a']
I can't find the correct query for MongoDB, "$elemMatch: likedInterns" is not working I want to find an Intern array that contains one of the elements from likedInterns array. Please help
  const likedInterns = company.likedInterns;
  const liked = url.searchParams.get("liked");
  const interns = await db.models.intern
    .find(
      search
        ? {
            name: { $regex: new RegExp(search, "i") },
          }
        : {} 
      /* Show only liked interns - Not working */,
      liked
        ? {
           _id: { $elemMatch: likedInterns  },
          }
        : {}
    )
    .sort({ updatedAt: -1 });
  return [interns, tags, userId, companyId];
}

Solution

  • Try to build your filter before the query and use the $in operator

    const likedInterns = company.likedInterns;
    const liked = url.searchParams.get('liked');
    let filter = {};
    if (search) filter = { ...filter, name: { $regex: new RegExp(search, 'i') } }
    if (liked) filter = { ...filter, { _id: { $in: likedInterns } } }
    const interns = await db.models.intern
      .find(filter)
      .sort({ updatedAt: -1 });
    return [interns, tags, userId, companyId];