How do I save a timestamp value to firestore using cloud functions.
I tried this (adding 30 days to the timestamp) but it ends up saving the value as a number
var now = new Date();
await docRef.update({
'subscription':{
package:req.query.package,
endDate: now.setTime(now.getTime()+(30 *24+60+60+1000))
}
})
If you want to add days to the date, then you should setDate() instead. By using setTime() you're setting the time instead of the date. See code below:
var now = new Date();
now.setDate(now.getDate() + 30);
await docRef.update({
'subscription':{
package: req.query.package,
endDate: now
}
})
For more information, you should check out this documentations:
Date.prototype.setDate()
Date.prototype.getDate()
Related
I'm creating a mongo database which stores array of objects of the following form
{
_id: 5ca37dc35b55092ab2b0980e,
driverID: 'cjttwclbr00ui0714y2dodxe2',
createdAt: 2019-04-02T15:20:35.021Z,
updatedAt: 2019-04-02T15:20:35.021Z, __v: 0
}
I want to filter those results which belongs to a particular driver based on the day and hour
eg: I want to get all the records which created on 2nd hour of today which belongs to a particular driver
How can I write find query or aggregation method based on this scenario?
I can get hour of the day using
const hour = new Date().getHours();
To get all the driver data b/w a particular hour
var date = new Date(); // for today
date.setHours(n,0,0,0); // n is the hour
var endHour = new Date();
endHour.setHours(n+1,0,0,0);
var query = {
driverID:driverId,
createdAt :{ $gte:date,$lt:endHour}
}
db.collection.find(query);
I am saving data into mongodb and the dates are in this format for instance
7/30/1960 (july 30, 1960) is ISODate("1960-07-30T05:00:00.000+0000"),
I want to find records created today(and i dont care about the time,so long as its today) and i have this
var start = new Date();
var end = new Date();
and to display the data
db.posts.find({created_on: {$gte: start, $lt: end}});
Will this work or must i convert my iso dates to another format first?.
You can alter the 'start' and 'end' variables before querying:
var start = new Date();
start.setHours(0,0,0,0); // remove time part from the date
var end = new Date();
end.setHours(0,0,0,0); // remove time
end.setDate(end.getDate() + 1); // add a day to the end date
and then you can use your query:
db.posts.find({created_on: {$gte: start, $lt: end}});
I want to fetch the Posts which are created within 24 hours in sails js. And I am using mongodb database. How do I get all those Posts which are created in past 24 hours.
You can create a date range that consists of 24 hours in the following manner.
Using the momentjs library, you can create a date with the extension methods subtract() and cast it to a JS Date with the toDate() method:
var start = moment().subtract(24, 'hours').toDate();
or with plain vanilla Date objects, create the date range as:
var now = new Date(),
start = new Date(now.getTime() - (24 * 60 * 60 * 1000));
Use the where() method to use the query the Posts model using the above date range query, given the field which holds the timestamp is called date:
Posts.find()
.where({ "date" : { ">": start } })
.exec(function (err, posts) {
if (err) throw err;
return res.json(posts);
});
Looking to query against the date only anyone encountered this?
Sample code:
////MODEL
module.exports = {
attributes: {
date: {
type: 'date',
required: true
}
}
};
////CONTROLLER
var today = moment().toISOString();
var queryObj = { date: today };
var newDay = { date: today };
Day.findOrCreate(queryObj, newDay).exec(function(err, day) {
console.log(day)
});
Obviously this creates a new record on each refresh, as the iso string will change with each passing second.
Thanks for the help!
Instead of querying for a single date, you can query for a date range that includes all of today. First, you'll need to actually create values for that range--I whipped this up using Moment, but there's probably a better way:
var begin = moment(moment().format("YYYY-MM-DD")).toISOString();
var end = moment(moment().format("YYYY-MM-DD")).add(1, 'days').toISOString();
Then you can use query operators to search the range:
var queryObj = {date: {'>=': begin, '<': end}};
Day.findOrCreate(queryObj, newDay).exec(function(err, day) {
console.log(day)
});
As always, be mindful of time zone issues!
I want to compare date from MongoDB and my date.
Also i read this and this post and I did not find an answer.
My Code :
today: function() {
var today = moment().format();
return Posts.find({createdAt : { $gte : today}}) // show posts created in "future" , so this function must return nothing
},
createdAt = moment().format();// in MongoDB
As a result this construction doesn't work, but if i compare lie this :
var today = moment().format();
var daystart = moment().startOf('day').format();
if (daystart > today){
console.log ("YES");
}
else if (daystart < today)console.log ("NO");
Return
"NO"
Anybody help ?
EDIT :
today: function() {
var today = moment().toDate();
var daystart = moment().startOf('day').toDate();
// console.log(today + daystart);
return Posts.find({createdAt : { $gt : today}})
},
week: function() {
var today = new Date();
return Posts.find({createdAt : { $lt : today}})
},
month: function() {
var today = new Date();
return Posts.find({createdAt : { $ne : today}})
}
createdAt = new Date();
The .format() method is a display helper function which returns the date string representation based on the passed token argument. To compare the date from MongoDB with the the current date and time, just call moment() with no parameters, without the .format() method and get the native Date object that Moment.js wraps by calling the toDate() method:
today: function() {
var now = moment().toDate();
return Posts.find({createdAt : { $gte : now }});
}
Convert date to MongoDB ISODate format in JavaScript using Moment JS
MongoDB uses ISODate as their primary date type. If you want to insert a date object into a MongoDB collection, you can use the Date() shell method.
You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats:
new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.
new Date("<YYYY-mm-ddTHH:MM:ss>") specifies the datetime in the client’s local timezone and returns the ISODate with the specified datetime in UTC.
new Date("<YYYY-mm-ddTHH:MM:ssZ>") specifies the datetime in UTC and returns the ISODate with the specified datetime in UTC.
new Date() specifies the datetime as milliseconds since the Unix epoch (Jan 1, 1970), and returns the resulting ISODate instance.
If you are writing code in JavaScript and if you want to pass a JavaScript date object and use it with MongoDB client, the first thing you do is convert JavaScript date to MongoDB date format (ISODate). Here’s how you do it.
var today = moment(new Date()).format('YYYY-MM-DD[T00:00:00.000Z]');
console.log("Next day -- " + (reqDate.getDate() + 1))
var d = new Date();
d.setDate(reqDate.getDate() + 1);
var tomorrow = moment(d).format('YYYY-MM-DD[T00:00:00.000Z]');
You can pass today and tomorrow object to MongoDB queries with new Date() shell method.
MongoClient.connect(con, function (err, db) {
if (err) throw err
db.collection('orders').find({ "order_id": store_id, "orderDate": {
"$gte": new Date(today), "$lt": new Date(tomorrow)}
}).toArray(function (err, result) {
console.log(result);
if (err) throw err
res.send(result);
})
})