Sequelize compare with current timestamp - node.js

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

Related

How to select items in prisma with date GTE > current date

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

Mongoose delete records after certain time

I have a mongoose Schema which looks like this:
const USERS_DATA = new Schema({
_id: Number,
name: String,
img: String,
date: Date,
phone: String,
article: String,
createdAt: {
type: Date,
required: true,
default: Date.now,
index: { expires: '3d' }
}
},
{
collection: "users",
_id: false,
}
);
I need to push data to this schema.
const User = mongoose.model("users", USERS_DATA);
function pushToDB() {
const newUser = new User({
name: INPUT.name,
img: INPUT.img,
date: INPUT.date,
phone: INPUT.phone,
article: INPUT.article,
});
newUser.save(function (err) {
mongoose.disconnect();
if (err) return console.log(err);
});
}
This data have to be deleted after 3 days when it was pushed to database. How to implement it in node.js? I found it really confusing and tried lots of code. Any answers are appreciated! Thanks
P.S. I use mongoDb Atlas
You should separate the process to push the data into the database from the process to delete it after 3 days. You have already the first part :).
For the second part, you can write a function deleteOldDocument. This function will query for documents in DB that are created for 3 days or more, and delete them. Then, you can run this function periodically, 1 time per day for example.
The pseudo-code, in case you need it :
async function deleteOldDocument() {
const 3DaysAgo = ...; // here you can subtract 3 days from now to obtain the value
// search for documents that are created from 3 days or more, using $lt operator
const documentToDelete = await User.find({"created_at" : {$lt : 3DaysAgo }});
// delete documents from database
.....
// recall the function after 1 days, you can change the frequence
setTimeOut(async function() {
await deleteOldDocument();
}), 86400);
}
// call deleteOldDocument to start the loop
deleteOldDocument();

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.

Sequelize query where createdAt date like today date

In Express framework I am using Sequelize. I want select user's first name and last who are registered a specific date match with createdAt field. My query is in below.
const userData = models.users;
var querystring = { where: {createdAt: {[op.like]: '%2018-09-27%'}}, attributes: ['first_name', 'last_name'] }
userData.findOne(querystring).then(function (userData) {
console.log(userData);
});
But I got error below....
Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.
Arguments:
[0] _isAMomentObject: true, _isUTC: false, _useUTC: false, _l: undefined, _i: %2018-09-27%, _f: undefined, _strict: undefined, _locale: [object Object]
Thanks in advance
You can use the date range query who are registered on a date.
use startTime = start of the day, endTime = end of the Day.
Model.findAll({
where: {
createdAt: {
$gt: startTime,
$lt: endTime
}
}
})

how to change date timezone in mongoose?

In model schema,
Using
updated: {
type: Date,
default: Date.now
In server.js
put(function(req, res) {
var query = {name: req.params.name};
// use our bear model to find the bear we want
Domain.find(query, function(err, domains) {
if (err)
res.send(err);
var domain = domains[0];
domain.password = req.body.password; // update the bears info
domain.updated = new Date();
// save the bear
domain.save(function(err, data) {
if (err)
res.send(err);
res.json({ status: 'success', message: 'domain updated!' }, data);
});
});
});
However,
In db side it shows,
"updated": "2016-02-27T16:20:42.941Z"
But, my timezone is UTC+02.00
So it should be like 18:20:42
What I'm doing wrong?
I'm using moment-timezone
npm install moment-timezone
const moment = require('moment-timezone');
const dateThailand = moment.tz(Date.now(), "Asia/Bangkok");
console.log(dateThailand); // "2018-08-20T16:35:14.033+07:00"
*** Asia/Bangkok +07:00
Schema in the mongoose.
const categorySchema = new Schema(
{
_id: {type: mongoose.Schema.Types.ObjectId, auto: true},
c_name: String,
created_by: String,
created_date: {type: Date, default: dateThailand},
updated_by: String,
updated_date: {type: Date, default: dateThailand}
}, {_id: false}
);
See up that created_date, updated_date: {type: Date, default: dateThailand }
Read more: http://momentjs.com/timezone/docs/
*If you using Robo 3T tool.
You can set "Display Dates In..."
Options > Display Dates In... > Local Timezone
:) Work for me.
The timestamps are timezone agnostic, stored as a unix timestamp. This timestamp will work across timezones, and node interprets it using current timezone of the server. The date you've shown is correctly stored. As soon as you'll retrieve it, if your server's timezone is UTC+2, it will show you correct time.
There is nothing wrong in your code. MongoDb saves date in UTC format no matter in whichever timezone you try to insert your date.
If you log domain.updated before saving in DB, result will be UTC+2 (your local time)
If you see updated column in DB, result will be in UTC
If you fetch updated column value from DB, then again result will be in UTC+2 (your local time)
I changed this,
var utc = new Date();
utc.setHours( utc.getHours() + 2);
domain.updated = utc;
Now it works.
You can create a Date Object from a specific UTC time:
new Date(Date.UTC(year, month, day, hour, minute, second))
Remember that no matter what you use to set time in mongoose schema, mongoose will always use UTC time, hence you need to dynamically allocate the UTC timestamp inside the Schema. Here it goes :-
var current = new Date();
const timeStamp = new Date(Date.UTC(current.getFullYear(),
current.getMonth(),current.getDate(),current.getHours(),
current.getMinutes(),current.getSeconds(), current.getMilliseconds()));
//Here goes your schema
const auditSchema = mongoose.Schema({
dateTime : { type: Date, default : timeStamp }
})
Using moment.js it is as easy as:
var moment = require('moment');
var utcDate = moment.utc().toDate();
Enjoy!

Resources