I want to only run a statement only if the object is not null. If it is null I want to not do anything. I want to be sure if there is a proper way to achieve this. For example I tried it on MongoDB Playground and it did not work. Here is the link to playground: https://mongoplayground.net/p/yOmRxML88zi
Here is the if-else statement I want to run:
db.collection.aggregate([
{...},
service_type ? { $match: { serviceType: service_type } } : null,
{...},
]);
So if the service_type is not null run the statement else skip to next object in the aggregation. What I want to do in this occasion is get the list of everything in database (objects) that contain certain service type given by the user.
The schema looks something like this:
const sellerSchema = new mongoose.Schema({
user_id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
...,
serviceType: [{ String }],
});
CodePudding user response:
If you're using Mongoose, I suppose you're writing your app using Javascript or TypeScript.
What prevent you, then, from building your query like this?
const aggregatePipeline = [];
if (service_type) aggregatePipeline.push({ $match: { serviceType: service_type }});
...
db.collection.aggregate(aggregatePipeline).exec()