I have the following schema:
User: {
...otherFields,
isDumb: false,
type: "A" // could be "A", "B", or "C"
}
I want to fetch all dumb
users by default and fetch by type
only if the type
is passed through the parameters.
static async getUsers(req: any, res: Response) {
const { type = "" } = req.params;
const queryPipeline = [
{
$match: {
isDumb: true,
type: // I want to only filter by type if the param is passed in
}
}
]
const users = await User.aggregate(queryPipeline);
So if my data was:
[
{
...otherFields,
isDumb: false,
type: "A"
},
{
...otherFields,
isDumb: true,
type: "B"
},
{
...otherFields,
isDumb: true,
type: "C"
}
]
and req.params.type
was "B", I should get back:
[
{
...otherFields,
isDumb: true,
type: "B"
}
],
if req.params.type
was undefined
, I should get all dumb
users
[
{
...otherFields,
isDumb: true,
type: "B"
},
{
...otherFields,
isDumb: true,
type: "C"
}
]
3
Answers
you just have to build an object and pass it to match
You can create the object using JS:
First, you don’t need to use Aggregation Framework for simple find query. You can use
find
method instead.Second, consider approach where you initialize the filter with
isDumb: true
, and add newtype
property only ifreq.params.type
exists.