Reputation: 724
I cannot see data matching status and name this way. When I run this, the status and name are searching separately. but I want to get the data matching both.
return await Product.find({
$or: [
{ status: args.status },
{ product_name: args.product_name}
]
}).sort({ createdAt: "desc" });
I tried filter and aggregate but I could not get the correct data.
status can be null
. $and
it doesn't work for me.
solved
let filter = {};
if (args.status) {
filter.status = args.status;
}
if (args.product_name) {
filter.product_name = args.product_name;
}
const result = await Product.find({
...filter
}).sort({ createdAt: "desc" });
return result;
Upvotes: 0
Views: 49
Reputation: 4034
If you want to find products where status == args.status
and product_name == args.product_name
you would pass a query object like this:
{
status: args.status,
product_name: args.product_name
}
Edit
It sounds like you want to build the filter document depending on available parameters. It might look something like this.
let filter = {}
if (args.status) {
filter.status = args.status
}
if (args.product_name) {
filter.product_name = args.product_name
}
You would then pass this filter object to the find
call.
Upvotes: 1