Midlaj K
Midlaj K

Reputation: 57

How to change the date format from a mongoose array of object to string on ejs view?

Here is my mongoose model

  var agentSchema = new Schema({
   
    name: String,
    debit: [{
        date: Date,
        amount: Number,
        hint: String,
     }],
  })

I need to get the date from debit array and change it to dd:mm:yyyy format on the ejs view

I have tried several ways with projection by datetostring conversion but it is working for only mongoose object not for array of object.

Upvotes: 0

Views: 310

Answers (2)

hhharsha36
hhharsha36

Reputation: 3349

You can make use of the $map pipeline operator inside the $project stage to apply a condition to each and every element of an array.

db.collection.aggregate([
  {
    "$project": {
      "name": 1,
      "debit": {
        "$map": {
          "input": "$debit",
          "as": "d",
          "in": {
            "date": {
              "$dateToString": {
                "date": "$$d.date",
                "format": "%d:%m:%Y",
                // "onNull": "" // If Required
              }
            },
            "amount": "$$d.amount",
            "hint": "$$d.hint",
          }
        }
      }
    }
  }
])

This will provide the following output.

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "debit": [
      {
        "amount": 23535,
        "date": "06:02:2021",
        "hint": "StringHint"
      },
      {
        "amount": 2355,
        "date": "16:03:2021",
        "hint": "StringHint1"
      }
    ],
    "name": "String"
  },
  {
    "_id": ObjectId("5a934e000102030405000001"),
    "debit": [
      {
        "amount": 25,
        "date": "22:06:2021",
        "hint": "StringHint2"
      },
      {
        "amount": 55,
        "date": "01:07:2021",
        "hint": "StringHint3"
      }
    ],
    "name": "String"
  }
]

Upvotes: 1

Deepak kumar jain
Deepak kumar jain

Reputation: 115

Get the individual components from Date object and place them on template file as per desired behavior

let day = debit[0].date.getDate();
let month = debit[0].date.getMonth();
let year = debit[0].date.getFullyear();

Upvotes: 0

Related Questions