Home > database >  I can't replace the value of an array returned by mongoose
I can't replace the value of an array returned by mongoose

Time:06-04

I have a notifications.find query (mongoose) that returns multiple sheets

Notification.find({id: id}, function(err, notifications){}

I need to convert the timestamp values that are returned like that

[                                                                                             
  {
    _id: new ObjectId("12934193c51a231b0165425a"),
    userid: '62921df1c14a2eea0efa9399',
    timestamp: 1653817696599,
  },
  {
    _id: new ObjectId("11934193c51a231b0165425a"),
    userid: '62921df1c14a2eea0efa9399',
    timestamp: 1653817696600,
  }
]

I tried this

notifications.forEach((element, index) => {

notifications[index].timestamp = new Date(notifications[index].timestamp);

});

and this code

new Date(notifications[index].timestamp);

seems to work by converting the timestamp of each value, but I can't replace it in the array

I've been on this issue for several hours

CodePudding user response:

Instead of forEach use map

const newNotifications = notifications.map((element, index) => {
  return {
    ...element,
    timestamp: new Date(element.timestamp),
   }
});
  • Related