Inserting a momentjs object in Meteor Collection

心已入冬 提交于 2020-01-11 04:38:26

问题


I have a simple Meteor collection and I am trying to insert a document that has a momentjs property into it. So I do:

docId = Col.insert({m: moment()});

However, when I try to get this document back with

doc = Col.findOne({_id: docId})

I get "Invalid date" for doc.m like so:

Object {_id: "wnHzTpHHxMSyMxmu3", m: "Invalid date"}

Anyone?!


回答1:


I strongly recommend storing dates as Date objects and using moment to format them after they are fetched. For example:

Posts.insert({message: 'hello', createdAt: new Date});

Then later when you want to display the date:

var date = Posts.findOne().createdAt;
moment(date).format('MMMM DD, YYYY');



回答2:


Moments are not designed to be directly serializable. They won't survive a round-trip to/from JSON. The best approach would be to serialize an ISO8601 formatted date, such as with moment().toISOString() or moment().format(). (toISOString is prefered, but will store at UTC instead of local+offset).

Then later, you can parse that string with moment(theString) and do what you want with it from there.

David's answer is also correct. Though it will rely on whatever Metor's default mechanism is for serializing Date objects, as Date also cannot exist directly in JSON. I don't know the specifics of Meteor - but chances are it's either storing an integer timestamp or just using Date.toString(). The ISO8601 format is much better suited for JSON than either of those.

UPDATE

I just took a glance at the docs for Meteor, which explain that they use an invented format called "EJSON". (You probably know this, but it's new to me.)

According to these docs, a Date is serialized as an integer timestamp:

{
  "d": {"$date": 1358205756553}
}

So - David's answer is spot on (and should remain the accepted answer). But also, if you are doing something other than just getting the current date/time, then you might want to use moment for that. You can use yourMoment.toDate() and pass that so Meteor will treat it with the $date type in it's EJSON format.




回答3:


If you would like to have moment objects on find and findOne, save it as a date then transform it on finding it. For example:

Posts = new Mongo.Collection('posts', {
  transform: function (doc) {
    Object.keys(doc).forEach(field => {
      if (doc[field] instanceof Date) {
        doc[field] = moment(doc[field]);
      }
    });
    return doc;
  }
});

Posts.insert({
  title: 'Hello',
  createdAt: new Date()
});


来源:https://stackoverflow.com/questions/20937448/inserting-a-momentjs-object-in-meteor-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!