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);
});
Related
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()
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 have a MongoDB model that contains a Date field whose type is defined as Date.now. Any date is converted to ISO date format. Inside the model the date is defined as :
xDate : {
type: Date.now,
required: true
}
I pass the current Date as :
var d = new Date();
var temp = d.toISOString();
var subStr = temp.substr(10,temp.length - 1);
var curDate = temp.replace(subStr, "T00:00:00.000Z");
console.log(curDate);
However the date is stored as an ISO String inside the MongoDB schema. I try to query it using Mongoose using the following query:
X.
find({
xDate: curDate
})
.exec(function(err, doc) {
var response = {
status : 200,
message : doc
};
if (err) {
console.log('Error');
response.status = 500;
response.message = err;
} else if (!doc) {
console.log("Documents against the date not found in database" ,curDate);
response.status = 404;
response.message = {
"message" : "Documents not found for " + curDate
};
}
res
.status(response.status)
.json(response.message);
});
I keep getting a blank json array inspite of the data being there. Inside the table the xDate is stored as YYYY-MM-DD format.
The date inside mongo is not stores in ISO string. If you save your model as Date.now, it will save a new Date object, not an ISO string. So one easy way of querying is to query by new Date() object.
Also note that your query is hard to be true, since you will have a hard time getting the exactly same date as your data is stored. I think better option for you is using $lt or $gt filters.
New query should look something like:
let currDate = new Date()
// change the date using class methods
X.find({
xDate: {$lt: currDate}
}).exec...
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);
})
})
How can I save DD/MM/YYYY format into mongodb database in date type?
After saving it into mongodb, when I retrieved, how can I convert it back to DD/MM/YYYY?
I am using Mongoose.
Better way to store dates in mongodb is store them by using native javascript date object.
They allows you to use some useful methods (comparison, map reduce, ...) in mongodb natively.
Then, you can easily get formatted date by using mongoose virtuals, e.x.:
// describe your schema
var schema = new Schema({
time: Date
}, {
toObject: { getters: true }
});
// schema.formatted_time -> DD/MM/YYYY
schema.virtual('formatted_time').get(function() {
var date = new Date(this.time);
return (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear());
});