Using MomentJS for Default Date in MongoDB Document - node.js

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

Related

How to updateMultiple documents in mongoose base on current value of document

I have the following mongodb model:
const schema = new Schema({
timezone: {
type: String,
},
datetimeBaseOnTimezone: {
type: Date,
}
})
I want to update the datetimeBaseOnTimezone with the current Date for each document in database based on the current timezone of each document this using a single query.
Something like this:
await Model.updateMany({},(element) => ({
datetimeBaseOnTimezone: new Date(new Date().toLocaleString('en-US', { timeZone: element.timezone }))
}));
Is there any solution similar to this approach?
Starting with a few assumptions:
the datetimeBaseOnTimezone string has the same format for all documents
the timezone string contains an Olson timezone identifier or a UTC offset
you are using MongoDB 4.2 or newer
You could use the pipeline form of update, along with the $dateFromString operator, which might look something like:
Model.updateMany({},[{$set:{datetimeBaseOnTimezone:{$dateFromString:{
dateString:"$datetimeBaseOnTimezone",
format: <see dateFromString docs>,
timezone: "$timezone",
onError: "$datetimeBaseOnTimezone",
onNull: "$datetimeBaseOnTimezone"
}}}])

Store wrong timezone in default date and time

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.

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

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.

Mongoose + CoffeeScript 'default' property - Getting it to work?

As you know, MongooseJS has a "default" property available. For instance, if I want a Date property on my object, and I want that date to automatically default to the time at which the record is created, I would define it in the schema as:
var myObject = mongoose.Schema({
date: {type: Date, default: Date.now}
});
Now, the problem with doing this in CoffeeScript is that default is a reserved keyword in JavaScript, so the CoffeeScript compiler automatically wraps default in double quotes, so this CoffeeScript code:
myObject = mongoose.Schema
date:
type: Date
default: Date.now
is compiled as:
var myObject;
myObject = mongoose.Schema({
date: {type: Date, "default": Date.now}
});
This results in the default parameter not working as intended. Perhaps I'm missing something but everything I have tried just is not working. I shouldn't need to manually set the date when saving the record, as the default keyword already provides this functionality.
Does anyone know how to get around this?
I have to admit I hate CoffeeScript and the like, but you probably might get around this by doing something like this:
var schema = {
type: Date
};
schema["default"] = Date.now;
myObject = mongoose.Schema(schema);
So, the solution to my problem was rather simple, and a rookie mistake: I forgot to specify the Date property to return in myObject.find()...

Resources