简体   繁体   中英

How to write an IF function on a mongoDB query

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

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

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