Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

151
Views
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?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report

0

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()}
});
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!