在MongoDB/Mongoose查询结果中,如何格式化日期?

3

我的 MongoDB 集合中有一个 ISODate 字段,我想将结果格式化为 dd/mm/yyyy。

我的模型:

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)

那就是查询和渲染的过程:

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

我正在使用 handlebars

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

现在的结果如下:

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

但我希望显示为:08/04/2020

有人能帮我解决这个问题吗?谢谢!

1个回答

5

我们可以使用$dateToString运算符来格式化日期,查看mongoDb文档

正如您所看到的,我们只能在聚合管道中的$project步骤中使用此$dateToString运算符

这是Mongo Playground中的一个简单示例mongoplayground

在您的示例中,我们可以执行相同的过程,但使用$lookup而不是populate

查询可能像这样

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"
        }
    }
])

完美!谢谢!! - Marcel Streicher

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接