如何在 Node.js 中格式化 Mongoose 的日期?

问题描述 投票:0回答:6

我正在尝试更改从 Mongo 数据库获取的日期的格式。目前它们看起来像这样:

Fri Sep 16 2011 19:05:17 GMT+0900 (JST)

我尝试给他们打电话

.toString('yyyy-MM-dd')
但没有任何变化。我不知道它们是
Date
对象还是只是原始字符串。

我已经尝试检查 Mongoose 手册并用谷歌搜索一堆,但还没有找到任何东西。

有什么想法吗?

javascript date mongodb node.js mongoose
6个回答
29
投票

做到这一点的现代方法是使用momentjs,既可以在节点中使用,也可以在浏览器中使用,超级有用且易于使用。对于当前的问题,在遵循所有文档要求后,我在节点中像这样解决了它:

var moment = require('moment');
var fomatted_date = moment(photo.date_published).format('YYYY-MM-DD');

photo.date_published
直接来自猫鼬。


24
投票

你必须先创建一个 Date 对象:

var date = new Date(dateStr);  // dateStr you get from mongodb

var d = date.getDate();
var m = date.getMonth()+1;
// ...

13
投票

定义你的模式怎么样:

var someSchema = new Schema({
    title: String,
    created: Date
});

s.t。日期作为

Date
对象存储在 mongoDB 中。因此,当您读回它时,您将拥有一个正确的
Date
对象,您可以在该对象上使用可用的方法。


4
投票

只需添加

date: { type: String, default: Date } 

输出将为:{ "date": "Sat Nov 28 2020 22:57:38 GMT+0530 (India Standard Time)" }


0
投票

创建于:{ 类型:日期, 默认值:当前日期 } 添加这个简单的行来表示当前日期和时间

输出:----- 2021 年 7 月 2 日星期五 10:45:26 GMT+0530(印度标准时间)


0
投票

我倾向于做的是,在架构中,我使用 Date 类型定义日期:

const exampleSchema = new mongoose.Schema({
    startDate: {
        type: Date,
        required: true  // or false, depending upon needs (plus other options, as needed)
    },
    endDate: {
        type: Date,
        required: true  // or false, depending upon needs (plus other options, as needed)
    },
    whateverDate: {
        type: Date,
        required: true  // or false, depending upon needs (plus other options, as needed)
    }
});

然后我为猫鼬模式定义一个实例方法:

// Returns a date in 'yyyy-MM-dd' format
exampleSchema.methods.formatDate = function(datePropery) {
    const newDate = new Date(this[dateProperty]);
    let formattedDate = `${ newDate.getFullYear() }-`;
        formattedDate += `${ `0${ newDate.getMonth() + 1 }`.slice(-2) }-`;  // for double digit month
        formattedDate += `${ `0${ newDate.getDate() }`.slice(-2) }`;        // for double digit day
    return formattedDate;
}

并且,定义猫鼬模型:

const Example = new mongoose.model('Example', exampleSchema);

后来,在我选择了一个特定实例之后(对我来说,这通常在 async 函数内),例如

const item = await Example.findOne({searchFor: searchTerm});

我可以通过以下方式获取格式化日期:

item.formatDate('startDate');     // for startDate field (see exampleSchema), or
item.formatDate('endDate');       // for endDate field (see exampleSchema), or
item.formatDate('whateverDate');  // for whateverDate field (see exampleSchema).

如果项目从 Express 传递到 HTML,例如:

res.render('mypage', {item});

然后可以在 HTML 中使用它(至少对于 ejs 视图引擎的情况):

<%= item.formatDate('startDate') %>
<%= item.formatDate('endDate') %>
<%= item.formatDate('whateverDate') %>

也许这有点啰嗦,尽管它对我来说效果很好。

© www.soinside.com 2019 - 2024. All rights reserved.