NodeJS MongoDB Find posts that are older than current date - javascript

So I have this code line here:
let advertisements = await Advertisement.find({created_at: {$lt: moment().valueOf()}});
This is what it does:
created_at: returns a timestamp when post was created at: 1551198203488.0
moment.valueOf() return me a current timestamp for example: 1551198203488.0
Now I need to write this code line that it only finds ads that are 1 hour old. Is is possible somehow ?
Also I storing and group2_date which store current timestamp BUT with 1 hour added to it like this: moment().add(1, 'h')

You can subtract one hour from the moment using .subtract function and then use $gte operator to obtain only the greater values/documents from the subtracted hours and less then from the current time.
let advertisements = await Advertisement.find({
"created_at": {
"$lte": moment().toDate(),
"$gte": moment().subtract(1, 'hours').toDate()
}
})

Related

admin.Firebase.Timestamp stores time 7 hours behind

I'm trying to store a timestamp in Firestore from Firebase Functions. However, the incorrect time is being recorded in Firestore.
For instance, I want to store the UTC time:
August 14, 2021 21hr (9pm)
Note: this code is in my Firebase Function
const date = new Date(Date.UTC(
csvRow.startDateYear,
csvRow.startDateMonth,
csvRow.startDateDay,
csvRow.startDateHour,
csvRow.startDateMinute
))
console.log(date); // prints 2021-08-14T21:00:00.000Z (correct)
console.log('date.getTime():' + date.getTime()); // prints 1628974800000 (correct)
const timeStamp = admin.firestore.Timestamp.fromMillis(date.getTime());
console.log('timeStamp.toMillis():' + timeStamp.toMillis()); // prints 1628974800000 (correct)
write.startDate = timeStamp;
But when I actually look at the Firestore and see what's recorded, I get this, a timeStamp that's 7 hours behind:
I've also tried Timestamp.fromDate(date) but got the same result
Firebase Firestore TimeStamps break apart when using hours because they do not have timezones built into them. They are meant to represent a greater period of time, not for specific timezones (hour).
Try this function and see if it works properly:
var myTimestamp = firebase.firestore.Timestamp.fromDate(new Date());
If you are attempting this with Cloud Functions try the following:
admin.firestore.Timestamp.fromDate()
Detailed documentation:
https://firebase.google.com/docs/reference/node/firebase.firestore.Timestamp

Moment js not adding hours and minutes to a specific time

I have a start time to which i would like to add an end time to.
for example
startTime=19:09
endTime=00:51 // 0 hours and 51 minutes
i want to add the 51 minutes to the 19:09 to make it 20:00.
I have tried multiple different scenarios as showing bellow but nothing is giving me the correct time
i tried
let [hour, minute] = endTime.split(':').map(Number);
this.endTime = Moment(startTime)).add({ hour: 'hours', minute: 'minutes' }) // also tried .add(hour,'hours').add(minute,'minutes')
which still outputs 19:09. its just ignoring my end time
i tried
Moment(endTime, 'hh:mm').add(Moment.duration(startTime)).format("hh:mm");
which gives me an output of 08:00 when it should be 20:00
What am i doing wrong?
i want to add the end time to a start time.
Keep in mind that my endTime is always changing so sometimes it could be 13:05 etc cause its a user input
There are three major issues with your code:
Creating a moment with a timestamp alone (ie something like moment('19:09') without a date) like you do is deprecated and throws an error. You either have to pass in a fully specified timestamp in RFC2822 or ISO format or explicitely tell the library, what input format you are using.
The object you are passing to the add() function literally is
{
hour: "hours",
minute: "minutes"
}
ie, instead of passing the numerical values for hours and minutes to add to your
moment, you are passing the strings "hours" and "minutes", which obviously
momentsjs can't handle.
The format hh:mm only accepts hours from 0 to 12. If you want a 24-hour clock you have to use HH:mm
Taking these issues into account, the following snippet works as expected:
let start = '2021-01-07 19:09',
duration = '0:51',
starttime = '19:09';
let [hour, minute] = duration.split(":");
//shorthand initialization for the argument
let endtime1 = moment(start).add({hour, minute}).toString();
//explicit definition of property names
let endtime2 = moment(start).add({hours: hour, minutes: minute}).toString();
//add hours and minutes separately
let endtime3 = moment(start).add(hour, "hours").add(minute, "minutes").toString();
//provide a format for the timestamp. momentsjs will take the current date for the date value
let endtime4 = moment(starttime, "HH:mm").add(hour, "hours").add(minute, "minutes").toString();
console.log(endtime1);
console.log(endtime2);
console.log(endtime3);
console.log(endtime4);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Also keep in mind, that for specifiying which part of the timestamp to manipulate, you can either use singular or plural wording. Ie
moment(...).add(4, "hour").add(17, "minute") and moment(...).add({hour: 4, minute: 17})
is equivalent to
moment(...).add(4, "hours").add(17, "minutes") and moment(...).add({hours: 4, minutes: 17})
respectively as can also be seen in the snippet with the creation of endtime1 and endtime2
You need to convert your duration into a single unit as minutes, seconds, days etc...
Then you can use the following snippet to add duration.
you can uses moment methods to convert your duration
const mins = moment.duration(10, "hour").asMinutes();
const someTime = moment('19:09',"HH:mm");
const data = someTime.add('51','minutes').format("HH:mm")
//More clever solution would be
const data2 = someTime.add(1, "hours").add(51, "minutes").format("HH:mm")
console.log(data)
console.log(data2)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

Mongo ISODate - how to check if 30 or more days passed? [duplicate]

This question already has answers here:
Find all documents within last n days
(3 answers)
Closed 3 years ago.
Struggling with creating a condition to check if 30 days have passed since specified ISODate in mongo.
The field name is creationDate, Im using find function, and I want to find only these, where 30 days have passed from creation date.
User.find({
creationDate: {
$gte: ...
}
});
In Javascript I would simply do something like
(+new Date() - +new Date(creationDate))/60/60/24 >= 30
In a brief, I want to find only these elements, where 30 days have passed from creating it in mongo db. Looking for any kind of help!
I think you just need calculate the 30 days before current time, and use it as the condition as follows:
let fromDate = new Date(Date.now() - 60 * 60 * 24 * 30 * 1000);
User.find({
creationDate: {
$gte: fromDate
}
});
Dates are a tricky topic, so I suggest you to use a dedicated library in order to avoid problems with them.
You can use momentjs:
const aMonthAgo = moment().subtract(30, 'days').toDate();
Then change your query to:
$lte: aMonthAgo
In this way you'll find only documents with a creation date lower than "a month ago".
The toDate() function is needed to get the native Date object from momentjs date type.
As per your need and for the date-related operations, I would suggest using date-fns library. You can simply write the query as
var subDays = require('date-fns/sub_days')
var olderDate = subDays(new Date(2019, 28, 3), 30)
await User.find({
creationDate: {
$gte: olderDate
}
});
For the function, you can take a look into date-fns/sub_days.

How can I customize when a week starts in a Keen IO query?

Is it possible to define the start and end day of a 'week' in the Keen IO query language? I have a query like:
var query = new Keen.Query("count", {
eventCollection: "add_to_carts",
timeframe: "previous_2_weeks",
interval: "weekly"
});
The default result of my query shows the week starting Sunday and running to Saturday, but I need my data to start on Saturday - is that possible?
What we want to do is find data for the current week and the previous week in one query (using intervals) and separate the two week's results for comparison - with each week running from Saturday to Friday.
It would be possible with absolute timeframes and a custom interval definition, like this:
var query = new Keen.Query("count", {
eventCollection: "add_to_carts",
timeframe: {
start: "2016-08-01",
end: "2016-09-12"
},
timezone: "US/Pacific",
interval: "every_7_days"
});
Instead of using "weekly", it uses a custom interval definition of "every_7_days". This would effectively be one query starting on a Saturday some time in the past, and you would get as many interval results as 7 day blocks from that Saturday - essentially creating previous week and this week in the response.
Here's a fiddle that shows this query and resulting chart.

Mongoose.js find yesterday's date in database

I want to find all the users created up until yesterday. This is my code to make the query string:
var today = new Date();
var a = today.getDate();
a--;
today.setDate(a);
var yesterday = today.toDateString();
and it returns something like: Sun Jan 17 2016... which IS yesterday's date, but the db stores the date in iso format like: "date" : ISODate("2016-01-13T13:23:08.419Z") so what I get is 2016-01-13T13:23:08.419Z. My problem now is that I can't use the yesterday variable to query the db for the users I need AND even if I could, I don't know how to find every registration not including the ones that took place today.
Any help? Thank you very much!
You are generating a date on the front end, and then pushing it back a day, which is totally fine for a lot of circumstances -
For this, since you are trying to find DB entries that occured, perhaps try querying the database with a timestamp ranged pulled from the ID's of each document in your database.
Here is some documentation on how to do that from mongoDB. https://docs.mongodb.org/v3.0/reference/method/ObjectId.getTimestamp/
I've also provided some additional resources that may help you figure out exactly what to query in regard to this method:
https://steveridout.github.io/mongo-object-time/
https://gist.github.com/tebemis/0e55aa0089e928f362d9
Some psuedo code:
1. Query documents in the database
2. Get a timestamp from the ID's of the documents in the database
3. Set a range of the timestamps
4. Compare returned timestamps vs a timestamp range variable (yesterdays date in this case)
5. Have the DB return only documents that are within the range
I hope this helps!
Try this, using Moment.js:
yesterday = moment().add(-1, 'days');
db.users.find({ "date": { "$lt": yesterday }});
Create a date object that represents the start of day today, use it to query your collection for documents where the date field is less than that variable, as in the following example
var start = new Date();
start.setHours(0,0,0,0);
db.users.find({ "date": { "$lt": start }});
This will look for users created up until end of day yesterday.
momentjs is a super handy utility for doing manipulations like this. Using the library, this can be achieved with the startOf() method on the moment's current date object, passing the string 'day' as arguments:
Local GMT:
var start = moment().startOf('day'); // set to 12:00 am today
db.users.find({ "date": { "$lt": start }});
For UTC:
var start = moment.utc().startOf('day');

Categories

Resources