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: