Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

223
Views
Is there specific way to do an if-else statement in javascript for mongodb using mongoose?

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 }],
});
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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()
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!