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?
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.
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) }}},
});