Compare date (moment.js) in MongoDB

2019-01-27 17:26发布

问题:

I want to compare date from MongoDB and my date.

Also i read this and this post and I did not find an answer.

My Code :

  today: function() {
    var today = moment().format();
    return Posts.find({createdAt : { $gte : today}}) // show posts created in "future" , so this function must return nothing
  },

createdAt = moment().format();// in MongoDB

As a result this construction doesn't work, but if i compare lie this :

var today = moment().format();
var daystart  = moment().startOf('day').format();
if (daystart > today){
  console.log ("YES");
}
else if (daystart < today)console.log ("NO");

Return

"NO"

Anybody help ?

EDIT :

  today: function() {
    var today = moment().toDate();
    var daystart  = moment().startOf('day').toDate();
    // console.log(today + daystart);
    return Posts.find({createdAt : { $gt : today}}) 
  },
  week: function() {
          var today = new Date();
      return Posts.find({createdAt : { $lt : today}}) 
  },
  month: function() {
            var today = new Date();
      return Posts.find({createdAt : { $ne : today}}) 
  }

createdAt = new Date();

回答1:

The .format() method is a display helper function which returns the date string representation based on the passed token argument. To compare the date from MongoDB with the the current date and time, just call moment() with no parameters, without the .format() method and get the native Date object that Moment.js wraps by calling the toDate() method:

today: function() {
    var now = moment().toDate();
    return Posts.find({createdAt : { $gte : now }});
}