Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

221
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda