data encountered at first instance of date is returned in sequelize - date

I wrote a query to get the data from the table where the data of today's date is to be fetched, if data for today's date isn't present, then the latest data from latest date in the past is fetched.
var db_data = await db.daily_tip({
where: { date_for_show: { [Op.lte]: payload_date }
})
where, if data encountered at the first instance which is less than the current date is fetched.
How do I modify this query to return the data as of this query
SELECT id,tip,date_for_show from daily_tip WHERE date_for_show <= '${payload_date}' ORDER BY date_for_show DESC LIMIT 1`

Just use order and limit options like this:
var db_data = await db.daily_tip({
where: { date_for_show: { [Op.lte]: payload_date },
order: [['date_for_show', 'DESC']],
limit: 1
})

Related

Prisma: Finding items where two fields have the same value

I would like to find items in a Prisma db where the values for two columns are the same. The use case is to compare the 'created_at' and 'updated_at' fields to find items that have never been updated after their initial creation. In raw SQL I would do something like:
select updated_at,
cast(sign(sum(case when updated_at = created_at then
1
else
0
end)) as int) as never_modified
from tab
group by updated_at
Is it possible to achieve this in Prisma?
You would need to use Raw Queries to compare time values from the same table.
Here's an example of how you could achieve this, assuming a PostgreSQL database for the following query.
import { PrismaClient } from '#prisma/client'
const prisma = new PrismaClient()
async function initiateDatesComparisonRawQuery() {
const response =
await prisma.$queryRaw`SELECT * FROM "public"."Project" WHERE "created_at" = "updated_at";`;
console.log(response);
}
await initiateDatesComparisonRawQuery();
you can use the preview feature fieldReference of prisma.
schema.prisma
generator client {
provider = "prisma-client-js"
previewFeatures = ["fieldReference"]
}
your code
prisma.project.findMany({
where: { created_at: prisma.project.fields.updated_at }
})

Sequelize.JS Returning the next earliest entry by date?

Im running into an problem where I want to query my database using sequelize.js to return, given the createdAt of one instance, the instance with the next earliest createdAt. for example: If I have 3 instances stored in database, created on Monday, Tuesday, and Wednesday. Given the ID or createdAt for the Tuesday instance, I want to return the Monday Instance.
Currently Im pulling all instances and sorting by date, but that is not an efficient solution at all.
This is my first Stack Overflow Question, so i'm not sure if I have the format down for asking questions yet.
Get an instance by ID
Select the next earliest instance passing createdAt of the instance:
const { Op } = require('sequelize')
...
const instance = await await db.yourModel.findById(id)
const nextEarliestInstance = await db.yourModel.findOne({
where: {
createdAt: {
[Op.lt]: instance.createdAt
}
},
order: [['createdAt', 'DESC']]
})

Construct Mongo ObjectId from timestamp with unique increment

I want to generate mongo objectid for the documents to be inserted as new with the timestamp value overwritten. so i used below code to get objectid.
var oIdWithTimestamp = function (timestamp) {
// Convert string date to Date object (otherwise assume timestamp is a date)
if (typeof (timestamp) == 'string') {
timestamp = new Date(timestamp);
}
// Convert date object to hex seconds since Unix epoch
var hexSeconds = Math.floor(timestamp / 1000).toString(16);
// Create an ObjectId with that hex timestamp
var constructedObjectId = mongoose.Types.ObjectId(hexSeconds + "0000000000000000");
return constructedObjectId
};
but if i want to insert 2 documents with same timestamp it doesn't fullfill the need. I noticed there is a get_inc function used to add incrementor value to objectids. And 16777214 different objectids can be generated using same timestamp. Any help regarding how to use this incrementor to get unique timestamp upto 16777214 is appreciated.
I have tried generating random mongo objectid using below snippet.
var bson = require('bson');
var generateObjIdFromTime = function(spefictime) {
spefictime = ~~(spefictime/1000);
return bson.ObjectID(spefictime);
}
It generates random mongo objectids with given timestamp.

Date comparison in MongoDB Filter

I am trying to create a Filter that will that will return the rows where at least one minute has passed from the stored transactionDate. I am not getting an error but it is not returning any rows. The transactionDate is a timestamp in MongoDB and is stored as "transactionDate" : ISODate("2016-09-30T20:29:19.448Z")
Thanks! \m/ \m/
var filter = Builders<MyDocument>.Filter.Eq("Genre", "Rock");
filter = filter & (Builders<MyDocument>.Filter.Lt(x => x.transactionDate, DateTime.Now.AddSeconds(Math.Abs(60) * (-1))));
using (var cursor = await MyCollection.Find(filter)
.Sort(Builders<MyDocument>.Sort.Ascending(x => x.artist).Ascending(x => x.rating)).ToCursorAsync())
{
// foreach...
}
The above code actually does work. I had an issue in the data causing no results to be returned. \m/ \m/

Change date storage format in MongoDB

In an input json file i receive dates in this format:
{ "dt_received" : "2016-01-22T12:35:52.123+05" }
When loaded into MongoDB, those dates are stored this way:
dt_received: "2016-01-22T07:35:52.123Z"
The issue is that i need the timezone to calculate my indicator.
In constraint, i can't create new columns such as "dt_received_timezone".
So i'm looking for changing the date storage format into MongoDB in order to make the timezone appear (or at least not disapear)
Is it a way to to this? Or any solution ?
If you receive data from various time zones and want to keep the time zone offset, you will have to save it into the database like this:
var now = new Date();
db.data.save( { date: now, offset: now.getTimezoneOffset() } );
You can then reconstruct the original time like this
var record = db.data.findOne();
var localNow = new Date( record.date.getTime() - ( record.offset * 60000 ) );
See the documentation for further details