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

261
Views
How to subtract timestamps and add that to the response in mongoose?

I have a attendance model that has reference to the class model The response that is returned has two createdAt dates

const attendanceInfo = await Attendance.find({
      student: studentId,
    })
      .populate('class', 'createdAt');
    res.json({ data: attendanceInfo });

But for each object in attendanceInfo i want one additional field difference and its value will be createdAt(of class model) - createdAt(of attendance model)

EDIT:

The response i am getting at the moment is

{
    _id: '614c6515a392d4a9dba59903',
    class: {
      _id: '614c5437a392d4a9dba59801',
      createdAt: '2021-09-23T10:17:27.706Z',
    },
    createdAt: '2021-09-23T11:29:25.984Z',
    updatedAt: '2021-09-23T11:29:25.984Z',
    __v: 0,
  },

And the result i am expecting is

{
    _id: '614c6515a392d4a9dba59903',
    difference: '01:11:58',
    class: {
      _id: '614c5437a392d4a9dba59801',
      createdAt: '2021-09-23T10:17:27.706Z',
    },
    createdAt: '2021-09-23T11:29:25.984Z',
    updatedAt: '2021-09-23T11:29:25.984Z',
    __v: 0,
  },
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I am using moment.js

const attendanceInfo = [{
    _id: '614c6515a392d4a9dba59903',
    class: {
      _id: '614c5437a392d4a9dba59801',
      createdAt: '2021-09-23T10:17:27.706Z',
    },
    createdAt: '2021-09-23T11:29:25.984Z',
    updatedAt: '2021-09-23T11:29:25.984Z',
    __v: 0,
  },{
    _id: '614c6515a392d4a9dba59904',
    class: {
      _id: '614c5437a392d4a9dba59802',
      createdAt: '2021-09-23T09:17:27.706Z',
    },
    createdAt: '2021-09-23T10:25:25.984Z',
    updatedAt: '2021-09-23T10:25:25.984Z',
    __v: 0,
  }]
  
attendanceInfo.map((elem)=>{
    let attendanceCreatedAt = moment(elem.createdAt);
  let classCreatedAt = moment(elem.class.createdAt);
  let differenceInsecs = attendanceCreatedAt.diff(classCreatedAt, 'seconds');
    elem.difference = new Date(1000 * differenceInsecs).toISOString().substr(11, 8)
})

console.log(attendanceInfo)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.2.1/moment.min.js"></script>

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!