Home > Net >  How to write an IF function on a mongoDB query
How to write an IF function on a mongoDB query

Time:06-04

I currently have the below code setup to retrieve some data from a MongoDB database and I would like to make an IF function that runs on the documents received. I am trying to have an IF function that runs if the price field in the documents are 10% higher than event.payload.base_price otherwise move on, I am fairly new to coding and MongoDB so can't figure this one out as I am not sure how to write this function. Any help would be incredibly appreciated.

async function run() {
  try {
    const query = { contract: idSplit[1] , id: idSplit[2] };
    const options = {
      sort: { name: 1 },
      projection: {_id: 0, slug: 1, contract: 1, id: 1, price: 1},
    };
    const cursor = listings.find(query, options);
    await cursor.forEach(console.dir);
  } finally {
    await client.close();
  }
}
run().catch(console.dir);

CodePudding user response:

After you get the array In the cursor, you can use below if conditions in the forEach Loop:

cursor.forEach((element) => 
    {
        if (element.price > event.payload.base_price   event.payload.base_price * 0.1) {
            console.log("Event is happening", element.price); 
        } else {
            console.log("Event is not happening", element.price)
        }
    });
  • Related