Home > Enterprise >  How to search for records by using a value in object array from mongoose?
How to search for records by using a value in object array from mongoose?

Time:05-23

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: []

CodePudding user response:

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.

CodePudding user response:

Please try this

const requests = await Request.find({
    itemsList: { $elemMatch: { item: mongoose.Types.ObjectId(id) }}},
});
  • Related