Home > Mobile >  Mongoose lte method not working for moment
Mongoose lte method not working for moment

Time:03-31

I am Fetching Date saved in db. Then, i am doing a small date maths to substract date from today from 3,Which is giving me Date in Format - (DD-MM-YYYY). Date saved in db format is also same - (DD-MM-YYYY). Can anyone help me out yrr... In Validating $lte for that date. I am not getting any log for DipData. Thanks in Advanced!


    nodeCron.schedule("* * * * *", async function () {
        var DateNow = await moment().subtract(3, "days").format("DD-MM-YYYY");
         console.log("Test Date Cron",DateNow);
        console.log("-->",new Date(DateNow.format("DD-MM-YYYY")));
    
        let DipData = await userModel.find({}, { LastAppOpenedTime: { $lte : new Date(DateNow.format("DD-MM-YYYY")) }})
        console.log("-----DipData ------->", DipData);
       
    });

CodePudding user response:

first thing you need to identify if there is date which is stored in document of mongo collection is string or regular date format or epoch format. If it's string the query may gives not accurate result. If there is date format or epoch format, you can easily queried your result with proper result.

  1. Therefore in case if there is string in LastAppOpenedTime document key you can have query with $toDate under find query.
  2. If key is not in string format in stored document following code will work.
var DateNow = moment().subtract(3, "days");
const DipData = await userModel.find({ LastAppOpenedTime: { $lte: new Date(DateNow) } });

For the above two scenario would work if your query is in accurate form like removing the first empty braces.

userModel.find({}, { LastAppOpenedTime: { $lte : new Date(DateNow) }})

to

userModel.find({ LastAppOpenedTime: { $lte : new Date(DateNow) }})

CodePudding user response:

Hello I got this working by making a few changes

    const DateNow = await moment().subtract(3, "days");
    console.log("Test Date Cron", DateNow);
    console.log("-->", new Date(DateNow));

    const DipData = await userModel.find({ createdAt: { $lte: new Date(DateNow) } });

    console.log("-----DipData ------->", DipData);
    res.status(200).json({ success: true, message: "Request was successful", DipData });

I noticed you had the .format("DD-MM-YYYY") at the end of your moment function but it returned a string that couldn't be converted with the new Date(DateNow). I removed mine when testing as the response from the moment was working fine without it.

And also I updated your userModel.find({}, { LastAppOpenedTime: { $lte : new Date(DateNow.format("DD-MM-YYYY")) }}) to remove the first empty {}. So you would have userModel.find({ createdAt: { $lte: new Date(DateNow) } });

  • Related