How to select items in prisma with date GTE > current date - node.js

Hi there I'm new and prisma and trying to select future dates in prisma and not grab any 'expired' days.
I'm seeing in the docs that there is a prisma.now() but cant see it in the console when I log out cosole.log(prisma)
Does anybody know a good solution to this?
My created_at is grabbing this format: 2022-01-13 12:00
app.get("/ques", async function (req, res) {
console.log("PRISMA", prisma.NOW());
const allQues = await prisma.que.findMany({
where: {
created_at: {
gte: prisma.NOW(),
},
},
});
res.status(200).send(allQues);
});

I'm not sure that such thing even exists? (prisma.NOW())
now() is just a function that you can use in your schema file to set default value, for example:
model User {
registeredAt DateTime #default(now())
}
In your app code you can just use regular Javascript Date object, for example:
const allQues = await prisma.que.findMany({
where: {
created_at: {
// new Date() creates date with current time and day and etc.
gte: new Date()
},
},
});

Related

sequelize nodejs search findAndCountAll by date if there is date and all time if there is not date

I wanna Request from nodejs Sequelize to mysql to data of a date that comes from query and there may not be any date
Actually I have no idea how to search by date but i thought it can be with params
can any one help me
Here is what I tried:
.findAndCountAll({
where: {
[Op.or]: [
{ createdAt: { [Op.eq]: moment("2023-01-15").toDate() } },
]
})
and when i send date from react as a string and in nodejs i change it to date time it will show the day before date
ex:
console.log(moment(2023-01-15).toDate())
// 2023-01-14T21:00:00.000Z
You can build your filter if date is present and use $between to filter the previous day:
const date = "2023-01-15";// Some date you received from the client or empty
let where = {};
if (date) {
// Filter day before date
const endDate = moment(date).toDate();
const startDate = endDate;
startDate.setDate(startDate.getDate() - 1);
where = {
from: { $between: [startDate, endDate] },
}
}
// Execute the query
.findAndCountAll(where);

How can I set correct timezone for a date field in Mongoose?

I'm using moment for generating time and date:
const moment = require('moment-timezone');
const emailModel = require('./api/models/emails');
sentTime=moment().tz('America/Los_Angeles').format();
console.log(sentTime); //console log shows correct time
emailModel.findOneAndUpdate({ _id: emailInfo._id }, {sentTime: sentTime }, { upsert: true },function (err, doc) {
if (err)
console.log(err);
});
And this is Schema that I'm using mongoose :
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const EmailSchema = new Schema({
.
.
.
sentTime: {
type: Date,
trim: true
}
.
.
.
});
Problem is:
Console log shows correct time 2020-01-07T12:23:00-08:00 BUT mongoose saved incorrect timezone in DB : 2020-01-07T20:23:01.000+00:00
Currently the default behavior of Mongodb is to: (From the docs)
MongoDB stores times in UTC by default, and will convert any local
time representations into this form.
As a solution (and rightly so) what they recommend is:
Applications that must operate or report on some unmodified local time
value may store the time zone alongside the UTC timestamp, and compute
the original local time in their application logic.
Update:
Since you are already using moment-timezone a simple way I would go about this is:
Change the EmailSchema to have a timezone field and create a Mongoose virtual field on that schema to get adjusted time.
const schemaOpts = { toJSON: { virtuals: true } };
const EmailSchema = new Schema(
{
sentTime: {
type: Date,
trim: true
},
timeZone: {
type: String
}
},
schemaOpts
);
EmailSchema.virtual("adjustedTime").get(function() {
return moment.tz(this.sentTime, this.timeZone).format();
});
//fetching data
const result = await EmailSchema.findOne({}).exec();
console.info("result::", result.toJSON());
//note that if using .lean() for performance which has a caveat on using .toJSON()
trick for this case is before save, you need to add time with date. Ex: 2021/01/02 ==> 2021/01/02 15:00:00, ofcouse hour is always equal or greater than 04:00:00. Becase without time, date will be 00:00:00 and mongo will convert it to default timezone and substract hour with 4.

How to fetch data when post the date is string in node js

In my application i want to fetch the record on the bases of date i am posting the date like this (2019-07-27) and in my mongodb the date stores like ("created_at" : ISODate("2019-07-27T16:01:24.636+05:00")) but i return empty object how can i solve this problems any body help thanks in advance.
this is my mongodb data
http://prntscr.com/opi9lm
this is my post request
{
"income_frequency" : "daily",
"from_date" : "2019-07-27"
}
this is my controller
const transactionsCredit = await driverTransactionModel.find( {
$and: [
{ user_id: req.userData.userId },
{ transaction_type: mainConfig.transactionType.moneyIn },
{ created_at: req.body.from_date }
]
} ).lean().exec();
var from_date = new Date('2019-07-27'.toISOString());
db.collection.findOne('from_date': {
$lte: from_date
}, function(err, doc) {
if (error) {
console.log(error);
} else {
console.log(doc);
}
});
Note: You can convert date to ISODate and then find documents from collection will resolve your issue.
You need to make 2 dates start date and end date and then match also in DB there's "created_at" which is in date format while date you received from the front end is in a string that's why you need to cast it to date first before matching in the query as
let startDate = new Date(req.body.from_date)
// this will give you date with utc time 00:00:00
let endDate = new Date(new Date(req.body.from_date).setUTCHours(23,59,59))
then match with start and end date in the query:
If you only want data of date of req.body.from_date
const transactionsCredit = await driverTransactionModel.find( {
user_id: req.userData.userId,
transaction_type: mainConfig.transactionType.moneyIn,
created_at:{$gte:startDate,$lte:endDate}).lean().exec();
If you want to fetch data greater than date(req.body.from_date)
const transactionsCredit = await driverTransactionModel.find( {
user_id: req.userData.userId,
transaction_type: mainConfig.transactionType.moneyIn,
created_at:{$gte:startDate}).lean().exec();

Sequelize compare with current timestamp

This is my code right now:
const Grace = sequelize.define('grace', {
userId: Sequelize.TEXT,
tribeName: Sequelize.TEXT,
server: Sequelize.TEXT,
hours: Sequelize.INTEGER,
date: Sequelize.DATE,
datef: Sequelize.DATE,
});
As you can see datef is stores as a date. datef is a future date. Example: current time + 36h
else if (command === 'showdb'){
var now = Date.now();
const gracep = await Grace.findAll({
where: {
datef: {
$gt: now,
},
},
});
}
What I want to do is to have it fetch the results in the db, where datef is greather than current timestamp.
The thing is datef is stored as: 2018-06-07 05:11:04.221 +00:00
And the var now is: 1528330290003
So I'm pretty sure that's the reason why it's not working, as it's outputing [], when it shouldn't.
Not sure what to do.
I've used date comparisons in Sequelize for WHERE clause when I want to compare something against the current date.
In my case I converted the current timestamp (from Date.now()) to an ISO string like so:
const now = (new Date()).toISOString();
I didn't have any problems when calling using an [Op.gte] or [Op.lte] operator to compare against the stored dates.
date.now() returns the number of milliseconds since midnight 01 January 1970 UTC. It is the same as new Date().valueOf()
here is what you can do
where : { datef : { [Op.gt]: new Date() } },
Sequelize documentation

How to store a full date format in mongoDB?

I'm trying to save data in mongoDB database,
I am send a full date format like this "Wednesday March 25 2015" for example,
When I make a http call to save some data including the date, the date format that actually being saved in mongoDB is UTC datetime like this: '2016-05-18T16:00:00Z',
How can I store the full date format in the databse?
my code for saving the data including the date is:
app.post('/postDiary', authenticate, (req, res) => {
var diary = new Diary ({
headacheLevel: req.body.headacheLevel,
headacheSide: req.body.headacheSide,
nausea: req.body.nausea,
aura: req.body.aura,
photophobia: req.body.photophobia,
phonophobia: req.body.phonophobia,
date: new Date(req.body.date),
location: req.body.location,
weather: req.body.weather,
_creator: req.user._id
});
diary.save().then( (diary) => {
res.send(diary);
}, (err) => {
res.status(400).send(err);
});
});
and the part of date in my schema is this:
date: {
type: Date,
default: new Date()
},
Hope you can help me with that, Thank you.

Resources