Home > other >  How to subtract timestamps and add that to the response in mongoose?
How to subtract timestamps and add that to the response in mongoose?

Time:10-08

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,
  },

CodePudding user response:

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>

  • Related