Mongoose lte method not working for moment - javascript

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 in validating $lte for that date. I am not getting any log for DipData.
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);
});

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.
Therefore in case if there is string in LastAppOpenedTime document key you can have query with $toDate under find query.
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) }})

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

Between two dates

I can't figure out why the findOne function doesn't work. My code
async getSign(childrenId: number, week?: number, year?: number) {
if (week && year) {
const startDate = moment().year(year).week(week).startOf("week").format("YYYY-MM-DD");
const endDate = moment().year(year).week(week).endOf("week").format("YYYY-MM-DD");
console.log(startDate, endDate);
const signature = await this.diarySignRepository.findOne({
where: {
childrenId,
date: {
$between: [startDate, endDate]
}
},
attributes: ['sign'],
});
return signature?.sign;
}
}
My request:
http://localhost:5000/diary/sign/get/1?week=11&year=2023
In database i have record:
|id |childrenId|date |sign|
|---|----------|----------|----|
|2 |1 |2023-03-17|true|
In console i get:
2023-03-12 2023-03-18
Executing (default): SELECT "sign" FROM "diary_sign" AS "DiarySign" WHERE "DiarySign"."childrenId" = '1' AND "DiarySign"."date" = '2023-02-18' LIMIT 1;
I don't understand why between doesn't work
Your SQL is incorrect:
SELECT "sign" FROM "diary_sign" AS "DiarySign"
WHERE "DiarySign"."childrenId" = '1'
AND "DiarySign"."date" = '2023-02-18'
LIMIT 1;
Your database has 2023-03-17 whilst you're searching for 2023-02-18.
As a sanity check, remove date: { $between: [startDate, endDate] }, your SQL query will then search over childrenId, returning the expected entry.
To search dates correctly, startDate and endDate must be Date objects, whereas you're using strings, fix that. (Apply .format("YYYY-MM-DD") in console.log for pretty printing.) If that doesn't work, we'll need to see diarySignRepository.findOne.

Date issue in js and mongoose

let date = "2021-07-31-T18:30:00.000Z"
date = new Date(date)
let nextDate = new Date()
// I have made a addDays function which returns a date.
nextDate = date.addDays(1)
Mongoose query:
$match: {
created: {
$gt: new Date(date),
$lte: new Date(nextDate)
}
}
I want to change the date from "2021-07-31-T18:30:00.000Z" to "2021-07-31-T00:00:00.000Z" so that my query can filter correct data. How can I achieve this?
I tried using setHours but it won't work.
I tried to convert the date string you declared but it kept failing.
I found that the date string you provided in ISO format "2021-07-31-T18:30:00.000Z" is not correct. The correct one should be "2021-07-31T18:30:00.000Z". The hyphen before T should be removed.

Comparing two date values in cypress

I'm trying to check if one date value that I get from the element in the app is less than today's date:
const todaysDate = Cypress.moment().format('DD/MM/YYYY')
it("Check date to be less or equal than todays", () => {
cy.get('.date', { timeout: 15000 }).eq(3).invoke('text').should('be.lte', todaysDate);
})
However I'm getting the following error:
Timed out retrying after 4000ms: expected '12/14/2020' to be a number or a date
Is there a way to convert the date I get from element to a datetime object?
You can use what JavaScript has to offer:
const date = new Date('12/14/2020');
so in the context of Cypress:
it("Check date to be less or equal than today", () => {
cy
.get('.date', { timeout: 15000 })
.invoke('text')
.then(dateText => {
const date = new Date(dateText);
const today = new Date();
expect(date).to.be.lte(today);
});
});
The moment library is deprecated, using dayjs is recommended instead. You'll need this when parsing custom date formats, which might not be supported by the Javascript Date constructor. Based upon your error message I assume the expected format should be MM/DD/YYYY instead of DD/MM/YYY.
it("Check date to be less or equal than todays", () => {
cy.get('.date', { timeout: 15000 }).invoke('text').then(actualDateText => {
const dayjs = require('dayjs');
const todaysDate = new Date();
const actualDate = dayjs(actualDateText, 'MM/DD/YYYY').toDate();
expect(actualDate).to.be.lte(todaysDate);
});
});

Querying a timestamp by date with Sequelize

I want to find some entries in my DB through the createdAt column, but just using the date. I am using postgres and the createdAt is a timestamptz. Here is an example of what an entry in it looks like: 2019-02-27 20:17:07.05+00
This is what the setting of my query looks like:
const dateString = momentDate.format('YYYY-MM-DD')
query.createdAt = { $iLike: `%${dateString}` }
Unfortunately this is not working and I am getting the following error:
retry-as-promised:error SequelizeDatabaseError: operator does not exist: timestamp with time zone ~~* unknown
Is the issue perhaps because I am using a string? What is the right way to query by date?
Using function DateDiff to get days from between createdAt and dateString. Need to cast dateString to datetime
var sequelize = require('sequelize');
var dateString = '01/03/2019';
yourModel.findAll({
where: sequelize.literal(`DATEDIFF(day,Cast(${dateString} as datetime), createdAt) = 0`)
})
.then(results => {
})
.catch(err => {
});

Mongoose Date Filter

I have data stored in a MongoDB database and I'm using Mongoose to query the data. I'm trying to run date queries against my data to return objects from the database that fall within the specified data-range.
My webform sends an API request to an external micro-service/api that is responsible for querying the data in the Mongo database. The API receives a single value that is representative of a number of days. eg: date: "7d". I then proceed to build the mongoose query like so:
if (data.date) {
const date = new Date();
const dateRange = data.date.slice(0, -1); // strip the "d" from "7d"
date.setDate(date.getDate() - dateRange);
query.start = { $lte: date.toISOString() };
console.log(query);
}
and an example date from my database is:
start: 2016-02-10T09:09:01.000Z
The query is then executed:
Call.find(query, function (error, docs) {
if (error) {
callback(error, null);
} else {
callback(null, docs);
}
});
and finally, an example of query:
{ approved: 1, start: { '$lte': '2016-02-09T14:24:29.115Z' } }
However, no matter what date I send to my API the response is always empty...
Use the actual date object for your query, not string as you are doing presently. Because mongo stores dates wrapped with the ISODate helper and the underlying BSON (the storage data format used by mongo natively) has a dedicated date type UTC datetime which is a 64 bit (so, 8 byte) signed integer denoting milliseconds since Unix time epoch, your query doesn't return anything as it will be comparing the date fields in mongo with an ISO formatted string.
So, drop the toISOString() conversion and use the date object:
if (data.date) {
const date = new Date();
const dateRange = data.date.slice(0, -1); // strip the "d" from "7d"
date.setDate(date.getDate() - dateRange);
query.start = { $lte: date };
console.log(query);
}
Call.find(query, function (error, docs) {
if (error) callback(error, null);
callback(null, docs);
});
Better yet, you can use the momentjs plugin that has a very intuitive and easy datetime manipluation API. One method you can use is the subtract() function to get the date object n number of days ago:
if (data.date) {
const dateRange = data.date.slice(0, -1); // strip the "d" from "7d"
const date = moment().subtract(dateRange, "days");
query.start = { $lte: date };
console.log(query);
}
Call.find(query, function (error, docs) {
if (error) callback(error, null);
callback(null, docs);
});

Categories

Resources