Search code examples
node.jsmongodbformathandlebars.jsisodate

Formatting date in find() mongoDB/mongoose query result?


My MongoDB collection have an ISODate field and I want to format the result to dd/mm/yyyy.

My model:

const Pedido = new Schema({
    id: {
        type: String,
        required: true
    },
    cliente: {
        type: Schema.Types.ObjectId, 
        ref: 'clientes',
        required: true 
    },
    date: {
        type:Date
    }
})
mongoose.model('pedidos',Pedido)

And that's the query and render:

var query = await Pedido.find().populate('cliente').lean().exec()
res.render("admin/pedidos",{pedidos: query})

I'm using handlebars

{{#each pedidos}}
<h5 class="ordem1">Pedido #{{id}} <small>{{date}}</small></h5>
{{/each}}

It's showing a result like that:

Wed Apr 08 2020 21:00:00 GMT-0300 (GMT-03:00)

but I want to show: 08/04/2020

Could anybody help me with this? Thank you!!


Solution

  • we can use $dateToString operator to format date, check the mongoDb Docs

    as you can see, we can use this $dateToString operator only in aggregate pipeline, in the $project step

    here is a simple example in mongo playground mongoplayground

    in your example, we could do the same process, but use $lookup instead of populate

    the query may be something like that

    Pedido.aggregate([
        {
            $match: {} // add your search here
        },
        {
            $lookup: { // this is the alternative to the populate
                from: 'clientes',
                localField: 'cliente',
                foreignField: '_id',
                as: 'clientes'
            }
        },
        {
            $project: { // add all the fields you need from the collection, if you need to omit something from the query results, just don't mention it here
                id: 1,
                clientes: 1,
                date: { $dateToString: { format: "%d/%m/%Y", date: "$date" } } // this will return the date in the format "dd/MM/yyyy"
            }
        }
    ])