Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

153
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda