How to get the latest and oldest record in mongoose.js (or just the timespan between them)

前端 未结 5 767
面向向阳花
面向向阳花 2020-12-12 23:59

Basic problem

I have a bunch of records and I need to get latest (most recent) and the oldest (least recent).

When googling I found this topic where I saw

5条回答
  •  孤街浪徒
    2020-12-13 00:08

    Mongoose 3.x is complaining about the [] parameter in your findOne calls as the array format is no longer supported for the parameter that selects the fields to include.

    Try this instead to find the newest:

    Tweet.findOne({}, {}, { sort: { 'created_at' : -1 } }, function(err, post) {
      console.log( post );
    });
    

    Change the -1 to a 1 to find the oldest.

    But because you're not using any field selection, it's somewhat cleaner to chain a couple calls together:

    Tweet.findOne().sort({created_at: -1}).exec(function(err, post) { ... });
    

    Or even pass a string to sort:

    Tweet.findOne().sort('-created_at').exec(function(err, post) { ... });
    

提交回复
热议问题