How to change DB Structure array of ObjectId to Objects without data loss?

I am trying to add likedAt in my DB Data, so I can see which user liked the post and at what time.
Currently, in my likedBy, we are just storing objectID of the User, it is like an array. But what I want it to store something like objectID as well as likedAt time when this entry was added.

`postSchema = new Schema(
{
title: {
type: String,
},
description: {
type: String,
},
image: {
type: String,
},

postedBy: {
  type: mongoose.ObjectId,
  ref: "User",
},
likedBy: [
  {
    type: mongoose.ObjectId,
    ref: "User",
  },
],

},
{
timestamps: {
createdAt: “created_at”,
updatedAt: “updated_at”,
},
}
);
`

Right now it is like this
"likedBy":[
{
“$oid”:“65b34vgvv2552f295”
},
{
“$oid”:“65b34ghh544351374c3f295”
}
],

I want it to be like this

likedBy: [
	{
         "$oid":"65b34ff40615fd354c3f295",
         "likedAt": "Date here"
      },
      {
         "$oid":"51315661651",
         "likedAt": "Date here"
      },
]

Helo @Bushra_Rashid_Baig, Welcome,

  • Change your schema to:
"likedBy": [
  {
    "id": {
      "type": mongoose.ObjectId,
      "ref": "User"
    },
    "likedAt": Date
  }
]
  • Migrate your data into collection
  • The $$NOW will set current date, you can pass external date if you want.
db.collection.updateMany({},
[
  {
    $set: {
      likedBy: {
        $map: {
          input: "$likedBy",
          in: {
            id: "$$this",
            likedAt: "$$NOW"
          }
        }
      }
    }
  }
])

Check the query in dummy data before executing in live database!