最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Date.now() not a number in Mongodb - Stack Overflow

programmeradmin0浏览0评论

This Meteor server code stores a property createdAt: Date.now() expecting a number which is the epoch time, but when I view the document in mongo shell, I get "ISODate(\"2016-12-25T22:31:09.553Z\")"

UsageCol.before.insert(function (userId, doc) {
  doc.userId = userId;
  doc.createdAt = Date.now();
  doc.period = new Date(doc.createdAt).getMonth() + 1 + '' + new Date(doc.createdAt).getFullYear();
});

Then, I wanted to change the date, so on the mongo shell I did:

db.users.update({'emails.0.address':'[email protected]'},{$set:{createdAt:'ISODate("2017-02-25T22:31:09.553Z")'}})

But now I get:

Exception while invoking method 'myMethod' TypeError: accMills.getMonth is not a function

let accMills = Meteor.user().createdAt;
let freeTime = accMills.setMonth(accMills.getMonth());

This Meteor server code stores a property createdAt: Date.now() expecting a number which is the epoch time, but when I view the document in mongo shell, I get "ISODate(\"2016-12-25T22:31:09.553Z\")"

UsageCol.before.insert(function (userId, doc) {
  doc.userId = userId;
  doc.createdAt = Date.now();
  doc.period = new Date(doc.createdAt).getMonth() + 1 + '' + new Date(doc.createdAt).getFullYear();
});

Then, I wanted to change the date, so on the mongo shell I did:

db.users.update({'emails.0.address':'[email protected]'},{$set:{createdAt:'ISODate("2017-02-25T22:31:09.553Z")'}})

But now I get:

Exception while invoking method 'myMethod' TypeError: accMills.getMonth is not a function

let accMills = Meteor.user().createdAt;
let freeTime = accMills.setMonth(accMills.getMonth());
Share Improve this question asked Mar 20, 2017 at 22:13 Fred J.Fred J. 6,04913 gold badges60 silver badges113 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

If you set createdAt as Date.now() it is not going to be set as a Date object but as a number that is the unix timestamp in milliseconds. So accMills.getMonth() is like 1490048577615.getMonth(): it doesn't make sense. Instead you should do new Date(accMills).getMonth()

If you want to save a date object, you should set createdAt as new Date():

UsageCol.before.insert(function (userId, doc) {
  doc.userId = userId;
  doc.createdAt = new Date();
  doc.period = doc.createdAt.getMonth() + 1 + '' + doc.createdAt.getFullYear();
});

Try this doc.createdAt = new Date().getTime() it will return the date into epoch time format

UPDATE: as @RobG ment Date.now() and new Date().getTime() is same.

Try this instead on set $set:{createdAt:new Date('ISODate("2017-02-25T22:31:09.553Z")')}

And n your freetime variable let freeTime = new Date(accMills).getMonth();

If you are trying to insert,update a new doc, use dateCreated : Date.now() from a js shell like intelliShell in STUDIO 3T for mongoDB which will give you a number as output.

发布评论

评论列表(0)

  1. 暂无评论