Home > Mobile >  Expiration date check Mongodb | javascript
Expiration date check Mongodb | javascript

Time:12-19

I want to check the expiration date of the purchased product and if the date is expired then I want to remove it.

The way I'm saving it to DB:

  let currentDate = new Date();
  let currentDateMiliseconds = currentDate.getTime();

  let courseExpiresMiliseconds =
    currentDateMiliseconds   90 * 24 * 60 * 60 * 1000;  // 90 Days validity
  let courseExpires = new Date(courseExpiresMiliseconds);

  let userPurchasedCourses = new usersPurchasedCourses({
    username: `${value_a}`,
    coursesList: JSON.parse(value_c.replaceAll(".", '"')),
    expirationDate: `courseExpires`,
    tran_date: tran_date,
    status: "VALID"
  });
  await userPurchasedCourses.save();

I'm getting the data:

let userCourses = await usersPurchasedCourses.find({
    $and: [{ username: req.body.username }, { status: "VALID" }],
   });

Here I want to have a list of only valid data. No expired ones. How may I do that?

CodePudding user response:

Simply use greater than condition with current date using $gt: new Date(),

let userCourses = await usersPurchasedCourses.find({
  username: req.body.username,
  status: "VALID",
  expirationDate: { $gt: new Date() }
});

CodePudding user response:

moment.js worked well for me.

if(moment(new Date()).isSameOrAfter(new Date(item.expirationDate))){
        console.log("expired");
      } else {
        item.coursesList.map((item2) => {
          userallcourses.push(item2);
        });
      }
  • Related