如何将MongoDB ISODate转换为与输入兼容[type =" date"]

时间:2017-05-05 13:30:44

标签: mongodb meteor angular-meteor

我遇到了一个问题,即我使用mongoDB将日期存储为对象的一部分,并且我使用Meteor和Angular在前端公开这些对象。它给我的东西几乎是正确的,但是由于我试图保持数据绑定的工作,我不知道如何操纵对象然后再将它们传给Meteor。

我相信我需要做的是修改与db.table.find()查询匹配的每个对象,然后再将其返回给Meteor。

表中的对象具有以下结构:

$('#img')
    .mousemove(function (event) {
        console.log('Mouse moved');
    })
    .mouseenter(function () {
        console.log('Mouse over');
    })

我发布的是这样的:

{
    date: ISODate(2017-05-04T14:00:00Z),
    note: "Foo"
}

前端像这样连接起来。

Meteor.publish('tasks', function tasksPublication() {
    var tasks = Tasks.find();
    return tasks;
});

这个的问题是日期的格式:它包括来自" T"的所有内容,当它不应该有输入日期字段的那部分时。 如何在离开数据库的路上修改对象?

1 个答案:

答案 0 :(得分:1)

您需要使用moment.js

等库格式化日期

meteor npm install moment --save

import moment from 'moment';

const date = ISODate(2017-05-04T14:00:00Z);

const formattedDate = moment(date).format('DD-MM-YYYY'); //04-05-2017

You can read all about formatting using moment here:

我之前没有使用过Angular,因此我不确定如何使用角度逻辑来实现它,但是如果你编写某种名为formatDate()的模块,你可以重复使用它一遍又一遍

import moment from 'moment';

const formatDate = (date) => {
    return moment(date).format('DD-MM-YYYY'); //change the format string to your preference
}

export default formatDate;

然后,您可以在应用程序中处理日期的任何地方使用该功能:

import formatDate from '/path/to/formatdate';