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

207
Visualizações
What is the correct way of saving values into a constant in mongoose?

I have a user model and I have used timestamps in it. I need to access the createdAt date and save it in a variable. I tried

const date = await User.find({
      serial: serialId,
    }).select('-_id createdAt');

But this is returning

[ { createdAt: 2021-09-23T10:47:24.400Z } ]

However the only thing that i want to be saved inside my date constant is

2021-09-23T10:47:24.400Z

that also as a Date()

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You are getting an array because find() returns all matches. Get the property from the first object. Use it with the Date() constructor to get your required value as date.

Try this:

const date = await User.find({
      serial: serialId,
    }).select('-_id createdAt');

let finalDate = new Date(date[0].createdAt);
console.log(finalDate);
about 4 years ago · Juan Pablo Isaza Relatório

0

Use findOne, it returns one document. documentation of findOne : https://mongoosejs.com/docs/api.html#model_Model.findOne

const date = await User.findOne({
          serial: serialId,
        }, '-_id createdAt').exec();
    
    console.log(date.createdAt)

or

const {createdAt :  date}= await User.findOne({
          serial: serialId,
        }, '-_id createdAt').exec();
    
    console.log(date)

const {createdAt :  date} = { createdAt: '2021-09-23T10:47:24.400Z' }
console.log(date)
let fromDate = new Date(date);
console.log(fromDate.getDate())

Also look here : https://docs.mongodb.com/manual/reference/method/Date/#return-date-as-date-object

about 4 years ago · Juan Pablo Isaza 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