Querying a timestamp by date with Sequelize - javascript

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

Related

Mongoose lte method not working for moment

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

TypeORM query all records from today

I am trying to query all records from today but I get nothing, so My question is:
How to query with date validations in TypeORM?
My code:
all = await connection
.createQueryBuilder(Earnings, 't0')
.addSelect('t3.id', 't3_id')
.addSelect('t3.UID', 't3_UID')
.addSelect('t3.name', 't3_name')
.addSelect('t3.chips', 't3_chips')
.addSelect('t3.tickets', 't3_tickets')
.addSelect('t3.masteredLevel', 't3_masteredLevel')
.addSelect('t2.UID', 't2_UID')
.addSelect('t2.name', 't2_name')
.addSelect('t2.rule', 't2_rule')
.addSelect('t1.id', 't1_id')
.innerJoin(Questions, 't1', 't0.questionID = t1.id')
.innerJoin(Lessons, 't2', 't1.lessonUID = t2.UID')
.innerJoin(Topics, 't3', 't2.topicUID = t3.UID')
.where('t0.challenge = 1')
.andWhere('t0.createdAt = :today')
.andWhere('t0.userID = :userID')
.setParameters({ userID: user.id })
.setParameters({ today: moment() })
.getRawMany()
Your .andWhere('t0.createdAt = :today') only selects rows created at the instant of today parameter. You have set this parameter as moment(), which is not a date.
Since we can safely assume no rows will be created in the future, your simplest solution here is: .andWhere('t0.createdAt >= :today'), which selects rows created AFTER 00:00 today.
You can combine the addWhere and setParameters into one:
.andWhere('t0.createdAt >= :today', { today: moment().toDate() }) // note moment.toDate()
Alternatively use the MySql CURDATE() function to get the current date:
.andWhere('t0.createdAt >= CURDATE()')
When you test this, I recommend that you turn on TypeOrm full logging so you can see the actual generated SQL and you will be able to quickly solve any problems. See TypeOrm logging.
For TypeORM + PSQL
Sort items by today's date
.andWhere('t0.createdAt >= CURRENT_DATE')

Query by date and time only, without year using SQLite

I am storing birthdays in my SQLite database, they are dates converted to my own timezone from another timezone, every hour I want to query my database to get the dates that are the same day and hour
// Stored in DB:
const date = parseFromTimeZone(`2020-${bdayReply} 13:42:00`, { timeZone });
// Query
const birthday = await Birthday.findOne({ where: { date: new Date() } });
// Generated query
query: SELECT "Birthday"."id" AS "Birthday_id", "Birthday"."userId" AS "Birthday_userId", "Birthday"."date" AS "Birthday_date", "Birthday"."birthdayConfigGuildId" AS "Birthday_birthdayConfigGuildId" FROM "birthday" "Birthday" WHERE "Birthday"."date" = ? LIMIT 1 -- PARAMETERS: ["2020-02-03T07:42:00.005Z"]
// Output of new Date() at the time of running the query
2020-02-03T07:42:00.023Z
// Example of record active in my DB at that point (date var from earlier)
2020-02-03 07:42:00.000
The ORM I'm using allows for raw queries as well, now I was wondering what my query should look like to return the above record in the example, or maybe I can use a date library like date-fns to convert the new Date() to match the format of the database, what would that look like?
If you want to use an SQL raw query, it should looks like this :
SELECT * FROM my_table WHERE MONTH(my_date) = MONTH(NOW()) AND DAY(my_date) = DAY(NOW())
In SQLite, the syntax is :
SELECT * FROM my_table WHERE strftime('%m',my_date) = strftime('%m','now') AND strftime('%d',my_date) = strftime('%d','now')

Date-fns is being received as null value on the backend

Frontend: React
Backend: SpringBoot
Date format on the BE: 2011-10-05T14:48:00.000Z
I've tried to use the date-fns to send the correct format from the FE to the BE application, ut even following the documentation, the BE is receiving null.
Salvar = async () => {
const {update} = this.state;
const {dtInclusao} = this.state.compra.dtInclusao
var result = parse(
dtInclusao,
"dd/mm/yyyy",
new Date()
)
const response = await api.post('SolicCompra/compra',
{...this.state.compra, dtInclusao: result}, {'Content-type':
'application/json'});
The expected format is dd/MM/yyyy.
Here are some date-fns helpers I use on a regular basis:
export const parseDate = dateString => {
return Date.parse(dateString.replace(/-/g, '/').replace('T', ' '))
}
export const formatDate = date => {
return format(date, 'dd/MM/yyyy')
}
The first will parse date and timestamps into a Date object. The second will take that date object and format it back to a string in the format you want.
Using these helper functions you can update your code to:
var result = formatDate(parseDate(dtInclusao))

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