I want to update the current date in yyy-mm-dd form so i can query it later but i m unable to insert date in the required format.here what i had did till
const sampleSchema = new mongoose.Schema({
username:String,
date:{
type:Date
}
});
const Sample = new mongoose.model("Sample", sampleSchema);
let currentDate=new Date
const sample = new Sample({
username:req.body.username,
date:currentDate.toISOString().split("T")[0]
});
sample.save()
I'm getting this
{
"_id": {
"$oid": "61b5862c6ff7ff297ae97d0c"
},
"user": "username",
"date": {
"$date": "2021-12-12T00:00:00.000Z"
},
"__v": 0
}
I want date in yyy-mm-dd format.
Use moment.js to convert the ISO formatted date into normal formatted date YYYY-MM-DD Don't try to store your own formate of date on MongoDB because it creates problems in querying data based on date and time. So update it into ISO and then convert it into different formate at the backend
Converting ISO formate Date into YYYY MM DD
date = new Date('2013-08-03T02:00:00Z');
date = moment(date).format('YYYY MM DD'); //result 2013 08 03
Converting YYYY MM DD formate into IOS formate
date = new Date('2013-08-03');
date = moment(date).format();
Another thing users can do is to store data in the form of a string
and use $gt, $gte, $lte and $lt operators for queries
Related
var todayOrderCount = await OrderDetails.find({ "createdAt": {$gte: Date()},status: 2}).count();
i need data according date choosing count
var todayOrderCount = await OrderDetails.find({"createdAt": { $gte: new Date() }, status: 2 }).count();
You should use new keyword before Date() in order to get date with date type, when you use it without new keyword it will return date as a string.
also check createdAt type in your db maybe its timestamp in that case use
new Date().getTime()
I am trying to create an api to get the data between two dates in NodeJS. My database is mongoDB, my data looks like this
_id:ObjectId("60ff19125474fa0ec45c2d1a")
username:"abc"
Date:"2021-7-26"
TimeIn:"2:02 PM"
TimeOut:"2:02 PM"
_id:ObjectId("6101f4a4676d8b2b743a2d58")
username:"abc"
Date:"2021-7-27"
TimeIn:"2:02 PM"
TimeOut:"2:02 PM"
_id:ObjectId("6102e1357ad1ed20d4642db0")
username:"abc"
Date:"2021-7-28"
TimeIn:"2:02 PM"
TimeOut:"2:02 PM"
_id:ObjectId("6104717cb025c025e8b2d15e")
username:"abc"
Date:"2021-8-01"
TimeIn:"2:02 PM"
TimeOut:"2:02 PM"
i want to fetch the data between two dates, i create an api to fetch data by date (single), need some modification to fetch it between two dates.
here is api to fetch data by date:
fetchHistorybydate =(req,res)=>{
var HistoryList = []
User.find({"username":req.body.username, "leave":{ $exists : false} },function(err,data){
for(var i =1 ;i<data.length;i++){
var NDate = data[i].Date;
if(NDate==req.body.date){
HistoryList.push(data[i])
}
}
if(err)
{res.status(300).json("Error")}
else{
var token = jwt.sign({
data: 'foobar'
}, 'secret', { expiresIn: "30 minute"})
res.status(200).json({AccessToken: token,data:HistoryList})
}
})
}
for example:
let say there are two calender on frontend one is for Fromdate and second is for Todate, if user select date from Fromdate calender this 2021-7-26 and from Todate calender this 2021-7-28 then it will only fetch the records from these dates.
the output should be, according to above data
_id:ObjectId("60ff19125474fa0ec45c2d1a")
username:"abc"
Date:"2021-7-26"
TimeIn:"2:02 PM"
TimeOut:"2:02 PM"
_id:ObjectId("6101f4a4676d8b2b743a2d58")
username:"abc"
Date:"2021-7-27"
TimeIn:"2:02 PM"
TimeOut:"2:02 PM"
_id:ObjectId("6102e1357ad1ed20d4642db0")
username:"abc"
Date:"2021-7-28"
TimeIn:"2:02 PM"
TimeOut:"2:02 PM"
Please help me how to do this.
You have to update the store Date object in the Date parameter of your database. After that, you'll be able to query by two date ranges. Currently, your Date parameter is a string, but, you have to convert it to a Date object.
Here is the solution after converting into Date object:
fetchHistorybydate = (req, res) => {
var query = {
username: req.body.username,
Date: {
$gte: new Date(req.body.Fromdate).toISOString(),
$lte: new Date(req.body.Todate).toISOString()
},
leave: { $exists: false }
}
User.find(query, function (err, data) {
if (err) { return res.status(300).json("Error") }
else {
return res.status(200).json({ data: data })
}
})
}
Note: No need to loop through the entire array again after retrieving the data. Because we already query from our database with the $gte and $lte parameters. Where $gte means greater than or equal and $lte means less than or equal.
You can also use $gt (greater than) and $lt (less than).
I have date something like this
"createdAt": "ISODate('2021-07-07T06:41:46.000Z')"
I have written below mongoose query to fetch records for today. But below query fetched empty.
let meeting = await Meeting.find({
createdAt : {$lt: new Date().toISOString(),$gte: new Date().toISOString()}
});
I have tried below one more way with static date, it worked. I want to fetch data on dynamic todays date.
let meeting = await Meeting.find({
createdAt : {
'$eq': new Date('2021-07-07T06:41:46.000Z')
}
});
Can someone help me on this
I'm assuming the type of "createdAt" field is Date in Mongoose schema (you should convert to Date if it wasn't the case).
Logic
When you want to filter documents on a specific day, you can use the condition:
0:00 the day <= createdAt < 0:00 the following day
For example, to filter meetings on 07/07/2021, the condition will be:
0:00 07/07/2021 <= createdAt < 0:00 08/07/2021
Coding
With that logic in mind, the code is pretty straightforward:
let today = new Date();
today.setHours(0,0,0,0); // set to 0:00
let tomorrow = new Date(today)
tomorrow.setDate(tomorrow.getDate() + 1)
let meeting = await Meeting.find({
createdAt : {$gte: today, $lt: tomorrow}
});
When working with date/time values then I recommend the moment.js library. Could be this one:
let meeting = await Meeting.find({
createdAt : {
$gte: moment().startOf('day').toDate(),
$lte: moment().endOf('day').toDate()
}
});
So the problem I'm currently having is :
I've a list of gym classes, which every class has an OpeningTime. I want to fetch all the classes from the current day, but. I'm not getting the same result locally and in production, cause for some reason, when Im deploying my backend to Heroku, the timezone is being setted by default to UTC (when I've a GMT-3 timezone).
Here is my query :
var now = moment();
var startOfDay = now.startOf('day').format();
var endOfDay = now.endOf('day').format();
var clasesDB = await Clase.find({ $and: [{ openingTime: { $gte: startOfDay } }, { openingTime: { $lte: endOfDay } }] })
So, like I said before, the problem is ocurring when, for example:
When I fetch the classes at my local time (Ex: 02-26-19 21:00hs ( GMT-3) ), the queries are actually showing the classes from 02-27, because, at MINE 21:00hs, on the server side is already 00:00, so, the date is not 02-26 anymore. And I dont want this kind of output.
How can I get a workaround to solve this?
Thanks in advance! :)
Don't use .format(), this makes a string. Compare directly Date values, i.e. use
var now = moment();
var startOfDay = now.startOf('day').toDate();
var endOfDay = now.endOf('day').toDate();
By default moment uses local times, so moment().startOf('day') returns midnight of local time. If you want to get midnight of UTC then use moment.utc().startOf('day').
If you don't rely on "local" time zone, then you can specify it like moment.tz("America/New_York").startOf('day')
No matter which time you need, never compare Date values by string, use always actual Date value.
By default in MongoDB a date field is stored in UTC, You can create a date with offset while writing to store it in your timeZone. But you've not done it while writing documents then you need to convert date field to your required timeZone while reading data from database. Check this below example.
JavaScript Code :
const today = new Date().toLocaleDateString(undefined, {
day: '2-digit',
month: '2-digit',
year: 'numeric'
}) // 02/26/2020. If your Heroic server is in different location then specify your locale in place of undefined - whereas undefined picks local time by default. Ex:- 'en-Us' for USA
Query :
db.collection.aggregate([
{ $addFields: { timewithOffsetNY: { $dateToString: { format: "%m/%d/%Y", date: "$openingTime", timezone: "America/New_York" } } } },
{ $match: { timewithOffsetNY: today } }, { $project: { timewithOffsetNY: 0 } }
])
Above query is written for New York timeZone, you can convert it according to your timeZone, In test url you can see 1st doc is not returned though it is on 2020-02-26 cause offset to New York as of today is 5hrs, So after converting date becomes as 2020-02-25.
Test : MongoDB-Playground
Ref : $dateToString
I have saved my date as timestamp, using the below logic:
var timestamp = Math.floor(new Date().getTime()/1000);
timestamp =145161061
Can any one help me out with the query?
I need to find records between dates and my date is stored in timestamp format as shown above.
If you have specified the type of the field to be date, then even if you store the date by giving the time stamp, it will get stored as Date.
To do a range query on date you can simply do something like this:
db.events.find({"event_date": {
$gte: ISODate("2010-01-01T00:00:00Z"),
$lt: ISODate("2014-01-01T00:00:00Z"),}})
But then if you have specified it as Number, then you can simply do a range query on the number like this :
db.events.find({"event_date": {
$gte: 145161061,
$lt: 145178095,}})
You can try kind of this query:
var startTime = 145161061;
var endTime = 149161061;
Books.find({
created_at: {
$gt: startTime,
$lt: endTime
}
});