1

I have a rest service that gets all Events stored in a mongodb and sorts them but how do I not show ones past the current day and time?

//return all events
router.get('/', function(req, res, next) {
    Event.find({}, null, {sort: {date: 1}}, function(err, events) {
        if (err) return next(err);
        res.json(events);
    });
});
jordanpowell88
  • 857
  • 3
  • 11
  • 25

2 Answers2

1

gonna point you to an old thread w/ this

Querying with mongoose and dates

Seems to be exactly what you need

Community
  • 1
  • 1
LostJon
  • 2,287
  • 11
  • 20
0

First you need to add a created (or however you want to name it, createdAt, etc.) to your Event model. You can use a function like this to automatically set the date on save:

var eventSchema = new mongoose.Schema({...});

eventSchema.pre('save', function(next) {
  var currentDate = new Date();
  this.created = currentDate;
  next();
});

Put this function right under where you defined your mongoose model.

Then you can use the $lt (less than) option supported by MongoDB:

router.get('/', function(req, res, next) {
    // Get date of yesterday
    var yesterday = new Date();
    yesterday.setDate(yesterday.getDate() - 1);
    // Find every event that was created yesterday or the days before.
    Event.find({ created: { $lt: yesterday } }, function(err, events) {
        if (err) return next(err);
        res.json(events);
    });
});

Reference:

Community
  • 1
  • 1
Jonas
  • 725
  • 5
  • 23
  • you might want to change the Date yesterday a bit. As it is now it will exclude events from the last 24h. FYI there is also the `$gt` (greater than) option. – Jonas Jan 05 '17 at 19:06