简体   繁体   中英

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

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM