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

204
Views
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 answers
Answer question

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 Report

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 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!