Mongoose MongoDB in Node.js - Saving datetime in local timezone - node.js

I am using Mongoose in NodeJS project. I have this schema:
let InventorySchema = new Schema({
name: String,
tradable: {
type: Date,
default: () => {
return new Date().getTime()
}
}
}, {
versionKey: false
});
I live in Prague (GMT+01:00). When I insert "line" into my document, tradable is set automatically (because of default) to datetime without GMT. For example time now is in my city 16:51 but into database its saved as 15:51
How to save correct datetime? NodeJS Date giving me correct datetime when it is called normally.
EDIT: Using Date.now not helping! Same output

Use getTimezoneOffset() It will provide you the offset :
var date = new Date(); //ex 2019-01-18T16:26:44.982Z
var offset = - date.getTimezoneOffset() / 60; //in your case 1
And you add the offset to your date.

Related

how to get findOne current date value in mongodb

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()

Fetching timestamp from firestore Cloud Functions nodejs

I am an interface where I have declared lastLogin as Date.
LastLogin looks like this:
export interface User {
lastLogin: Date,
}
I am fetching this timestamp in my cloud function and I want it as a timestamp so that I can subtract it from the current Timestamp.
const mentor: User = mentorDoc.data() as User;
const login = mentor['lastLogin'];
const lastOpen = mentor['lastLogin'].valueOf();
const currentTime = new Date().getTime();
const diffMs = (currentTime - lastOpen);
const diffHrs = Math.floor((diffMs % 86400000) / 3600000); // hours
Last open shows like this :
063740174400.000000000
And when I use to like this :
const lastOpen = new Date (mentor['lastLogin'].valueOf());
Output:
undefined
Please change Date to firestore Timestamp both in the interface declaration as well as the collection field that holds the date in the firestore console
export interface User {
lastLogin: firebase.firestore.Timestamp,
}
You can now retrieve the date and also update it, this time simply by passing a new Date object.
// Read currently saved Timestamp
const ref = db.collection<User>('users').doc(`${uid}`).get().toPromise()
const saved_date = ref?.data().lastLogin
const current_date = new Date()
// if you just want the Date difference in ms after retrieving the timestamp from firestore.
const diff = current_date.getMilliseconds() - (saved_date.toDate()).getMilliseconds() // Timestamp -> Date (ms)
// Update Timestamp using a Javascript Date object
db.collection('..').doc('..').set({ lastLogin: current_date }, {merge:true})
// set creates the field while update works only if field already exists

Mongoose conditional field value

I am working on a project with NodeJS and MongoDB and I am using Mongoose. In my database I am storing the companies with the opening and closing hours. I also have a field isOpen which is a boolean and I want to know if it's possible to dynamically change the value of isOpen in mongoDB according to current date and the the opening hours of the company.
{
openingHours {
opens: Number,
closes: Number
},
isOpen: Boolean // should depend on the current date and openinghours
}
PS: I saw that it was possible to put a function over the field required.
You could use virtual property to get that functionality.
var storeSchema = new Schema({
openingHours {
opens: Number,
closes: Number
},
});
storeSchema.virtual('isOpen').get(function () {
const currentTime = Date.now();
const currentHour = currentTime.getHours();
return this.openingHours.opens >= currentHour && currentHour < this.openingHours.closes;
});
More information about virtual property you can find in official documentation.

How to save mongoose date-time in particular time-zone

Mongoose is saving date-time as ISODate("2017-04-25T09:40:48.193Z")in UTC format. How can i change its time zone to my local server timezone. So i need not to change the time every time i retrieve it from db. Here is my model schema:
var MyModelSchema = new mongoose.Schema(
{
id: Number,
description: String,
created: {type: Date},
modified: {type: Date, default: Date.now},
},
{
collection: 'my'
}
);
PS: I am aware that it is preferred to save time in UTC format but here my requirement is to save it in specified time-zone.
you can save users timezone and while updating add the time zone value to this new object. Better to use moment.js to convert this.
moment
Even thought it is not a good practice to store time in local format but this might help -
date = new Date(); //2017-04-25T06:23:36.510Z
date.toLocaleTimeString(); //'11:53:36 AM'
localDate = ""+d; //'Tue Apr 25 2017 11:53:36 GMT+0530 (IST)'
changes will be done where you are saving the Object -
var date = new Date(); //2017-04-25T06:23:36.510Z
date.toLocaleTimeString(); //'11:53:36 AM'
var localDate = ""+d; //'Tue Apr 25 2017 11:53:36 GMT+0530 (IST)'
var newModel = new ModelSchema()
newModel.description = 'Something';
newModel.created = locaDate;
newModel.save(function(err) {
if (err)
throw err;
return done(null, newUser);
});
I think I have a solution. Try this one for Asia/Calcutta this can be stored as Date type in Mongoose
function getCurrentIndianDateTime(){
var moment = require('moment-timezone');
var time = moment.tz('Asia/Calcutta').format("YYYY-MM-DDTHH:MM:ss");
return new Date(time);
}

Mongoose date comparison

My application will allow user to create coupons.
Coupon will be valid in datefrom and dateto period.
The thing is that every coupon should be valid for selected days, not hours.
For example since Monday(2016-06-12) to Tuesday(2016-06-13), so two days.
How should I store dates on server side and then compare it using $gte clause in Mongoose?
Thank you :-)
{ "_id" : 1, "couponStartDate" : ISODate("2016-06-26T18:57:30.012Z") }
{ "_id" : 2, "couponStartDate" : ISODate("2016-06-26T18:57:35.012Z") }
var startDate = new Date(); // I am assuming this is gonna be provided
var validDate = startDate;
var parametricDayCount = 2;
validDate.setDate(validDate.getDate()+parametricDayCount);
CouponModel.find({couponStartDate: {$gte: startDate, $lte: validDate}}, function (err, docs) { ... });
You can store expiration time as UNIX timestamp. In your Mongoose model you can use expiration : { type: Number, required: true}
If you have user interface for creating coupons then you can configure your date picker to send time in UNIX timestamp.
Or If you are getting Date string then you can use var timestamp = new Date('Your_Date_String');
And for calculation of Days you can use Moment JS. Using this you can calculate start of the date using .startOf(); and end of date using .endOf();
Timestamp return from Moment JS can be used for Mongoose query like $gte : some_timestamp and $lte : some_timestamp
If you want to validate the coupon before it is persisted, you can create a max / min value for the date field:
See this sample from official mongoose documentation on DATE validation:
var s = new Schema({ dateto: { type: Date, max: Date('2014-01-01') })
var M = db.model('M', s)
var m = new M({ dateto: Date('2014-12-08') })
m.save(function (err) {
console.error(err) // validator error
m.dateto = Date('2013-12-31');
m.save() // success
})
Hint: use snake_case or camelCase for field names

Resources