Store wrong timezone in default date and time - node.js

I am trying to store default date and time using mongoose with the Node.JS but somehow, it is storing different time zone value in database. I'm using "MongoDB Atlas Database" as a DB server and also configured default time zone with reference to this. I have also tried this for change time zone and also tried "moment-timezone.js", But didn't get any luck.
I just want to store default date and time with Indian standard time format.
Following is my code for the schema.
const testSchema = new mongoose.Schema({
from: String,
to: String,
amount: Number,
message: {
type: String,
default: ""
},
creationdate: {
type: Date,
default: Date.now
}
});
Please help me with this issue. Show me the best way to solve this problem.

MongoDB stores Date fields as a UTC timestamp in milliseconds since the Unix epoch, which is a 64bit integer (53bit in JS). This is also what Date.now() is. There is no timezone component to the data by design.
If you need a consistent timezone format for a Date object, add a virtual field that returns the required timezone adjusted string or object from the date.
const testSchema = new mongoose.Schema({
creationdate: {
type: Date,
default: Date.now
}
});
testSchema.virtual('formattedCreationDate').get(function() {
return this.creationdate.toLocaleString(); // or day.js/luxon
});
If you need a timezone other than the user or system supplied value, store the required TZ data in another field and use that timezone field in the virtual formatting.
The virtual will probably be easier if you use day.js or luxon.

Related

how to fix the date error using Date.now()

I am using Date.now() to get the current date and time, but I didn't know the problem I am having. The scenario is this that I use console to check whether date.now() generating correct time or not? Unfortunately I got the correct date in Unix code value convert and check that was correct time and date but when I put that in mongoo schema it used few hours back and store date with few hours back time. But when I get that object with date it returns me the few hours back date and time but when I bind that with Angular front it shows me the correct time the time I put on mongoo the problem is I am not able to filter data by date bcs that object contain few hours back time.
Here is the typescript object that I am pushing on the mongoo
bill = {
orderArray: [],
//investment total
totalActual:0,
//sale total
totalSale: 0,
//investment - sale
totalSave: 0,
quantity: 0,
date: Date.now()
}
and here is the mongo schema:
var cartSchema = mongoose.Schema({
orderArray: Array,
date: { type: Date, default: Date.now },
totalActual: Number,
totalSale: Number,
totalSave: Number,
})
Please check to whether your DB server and application running in the same timezone
Or convert your local time to UTC format from application side and pass it MongoDB

Passing current time to Mongoose query

I've run into problem. I made field in my Mongoose schema with type "Date":
...
timeOfPassingQuestion: Date,
...
Now, I want to pass current time in hours, minutes, seconds and miliseconds and save it into that field. How should I format my Node variable so I can pass it without errors?
Edit: Also, I forgot to say that I wanna later see how much time user spent answering question by subtracting current time and time that I pulled from DB, timeOfPassingQuestion field.
This is the syntax to create a schema that supports a date field:
// Schema
{ //...
someDate: Date,
}
// date object that you can use whenever you decide to set it
var dateObj = new Date();
This will create a JavaScript date object that you can then pass into your Mongoose object for the date field.
Or, if you will always want it on creation, put it directly in your mongoose schema
{ //...
createdDate: { type: Date, default: Date.now },
}
In order to compare the time in the future, I suggest you use moment.js, then you can query the time difference like so:
moment(Model.createdDate).fromNow();
Sources:
Mongoose Schema
Moment.js fromNow

Using MomentJS for Default Date in MongoDB Document

I'm trying to use MomentJS to get non-localized UTC time and set that as the default for new documents created in Mongo.
var SubFavoriteSchema = new Schema({
user : { type: String, ref: 'Account'},
date : {type: Date, default: moment.utc()}
});
The problem is, moment.utc() returns the date that the Node server started. Thus if I start the server on Jan 1, all the documents get a UTC time of Jan 1, even if the document is created on Jan 10.
Any idea why it keeps getting the server's start time instead of the current time?
The problem is that you're calling the moment.utc() function (once) when creating the schema, so the same resulting value is used when creating new documents.
However, you don't need to use moment for this, default: Date.now will do what you want as that function returns the current UTC time. Note that you don't call the now function, you just pass the function itself. That's the key difference.
You need to use a factory function for that.
var currDate(){
return function(){
return moment.utc();
}
}
var SubFavoriteSchema = new Schema({
user : { type: String, ref: 'Account'},
date : {type: Date, default: currDate()}
});

Sequelize went wrong when saved date in nodejs

I tried to store an object to Mysql with Sequelize, Nodejs. Every things did ok, excepted the timestamp went wrong. There are my lines:
var log = {
id: id,
error_code: error_code,
created_at: moment().format('YYYY-MM-DD HH:mm:ss'),
updated_at: moment().format('YYYY-MM-DD HH:mm:ss')
}
models.ErrorLog.create(log).then(function(log){
console.log('Create Log');
console.log(log);
});
Focus on these two timestamp fields, I have logged and saw it was right when I created it.
var log = {
created_at: '2016-11-16 22:51:24',
updated_at: '2016-11-16 22:51:24'
}
But, It is wrong in the mysql record:
{
created_at: '2016-11-17 05:45:34',
updated_at: '2016-11-17 05:45:34'
}
In MySql, these fields are defined as:
- created_at: timestamp, nullable
- updated_at: timestamp, nullable
It is very basic, so I don't know what happened. It's so strange!
Where is my mistake?
Use the Sequelize options.timezone property when creating your database connection to make sure that the application and MySQL server are both set to the same timezone offset.
[options.timezone='+00:00']
String
The timezone used when converting a date from the database into a JavaScript date. The timezone is also used to SET TIMEZONE when connecting to the server, to ensure that the result of NOW, CURRENT_TIMESTAMP and other time related functions have in the right timezone. For best cross platform performance use the format +/-HH:MM. Will also accept string versions of timezones used by moment.js (e.g. 'America/Los_Angeles'); this is useful to capture daylight savings time changes.

MongoDB date index

I am using node.js and mongodb for my small application and I want to index my document by date object. For Example
var MySchema = new Schema({
created_at: { type: Date, default: Date.now }
});
myschema.index({created_at: -1});
But how I understand, each object will have nearly unique create_id field. Wouldit work well ? and would this method give me effect. If you can, please also send me any articles about mongodb date indexing.

Resources