skip to Main Content

I want to search for records using the below-mentioned Field and code I have used, returning nothing. I’m sure I’m querying wrongly, and can anyone help me build the correct query code?

Field I wanted to serach

Code I have used:

const { id } = req.params;

const requests = await Request.find({
    itemsList: { item: id },
});

Return:

console.log(requests);

requests: []

2

Answers


  1. const requests = await Request.find({
        "itemsList.item": id,
    });
    

    will return the entire array if there is a match.

    Playground

    And make sure your data on the query part is matching the type.

    In the image, you have a string. Use ObjectId if it is ObjectId.

    Login or Signup to reply.
  2. Please try this

    const requests = await Request.find({
        itemsList: { $elemMatch: { item: mongoose.Types.ObjectId(id) }}},
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search