首页 文章

如何在mongoose.js中获取最新和最旧的记录(或者只是它们之间的时间 Span )

提问于
浏览
28

基本问题

我有一堆记录,我需要得到最新的(最近的)和最老的(最近的) .

谷歌搜索时发现this topic我看到了几个问题:

// option 1
Tweet.findOne({}, [], { $orderby : { 'created_at' : -1 } }, function(err, post) {
  console.log( post );
});
// option 2
Tweet.find({}, [], {sort:[['arrival',-1]]}, function(err, post) {
  console.log( post );
});

不幸的是他们都错了:

TypeError: Invalid select() argument. Must be a string or object.

链接也有这个:

Tweet.find().sort('_id','descending').limit(15).find(function(err, post) {
  console.log( post );
});

那一个错误:

TypeError: Invalid sort() argument. Must be a string or object.

那么我该如何获得这些记录呢?

Timespan

更理想的是,我只想要最旧和最新记录之间的时间差异(秒?),但我不知道如何开始这样的查询 .

这是架构:

var Tweet = new Schema({
    body: String
  , fid: { type: String, index: { unique: true } }
  , username: { type: String, index: true }
  , userid: Number
  , created_at: Date
  , source: String
});

我很确定我有最新版本的mongoDB和mongoose .

编辑

这就是我根据JohnnyHK提供的答案计算时间 Span 的方法:

var calcDays = function( cb ) {
  var getOldest = function( cb ) {
    Tweet.findOne({}, {}, { sort: { 'created_at' : 1 } }, function(err, post) {
      cb( null, post.created_at.getTime() );
    });
  }
    , getNewest = function( cb ) {
    Tweet.findOne({}, {}, { sort: { 'created_at' : -1 } }, function(err, post) {
      cb( null, post.created_at.getTime() );
    });
  }

  async.parallel({ 
    oldest: getOldest
  , newest: getNewest
  }
    , function( err, results ) {
      var days = ( results.newest - results.oldest ) / 1000 / 60 / 60 / 24;
      // days = Math.round( days );
      cb( null, days );
    }
  );
}

3 回答

  • 61

    我们有一个叫做排序的方法,我们可以收集 get first element(old document) which means 1 for sort fieldlast element(new document) which means -1 for sort field .

  • 4

    对于版本~3.8 mongoose

    找到最后一个条目

    model.findOne().sort({ field: 'asc', _id: -1 }).limit(1)
    

    或使用

    model.findOne().sort({ field: -_id }).limit(1)
    
  • 0

    Mongoose 3.x抱怨 findOne 调用中的 [] 参数,因为选择要包含的字段的参数不再支持数组格式 .

    试试这个,找到最新的:

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

    -1 更改为 1 以查找最旧的 .

    但是因为你没有使用任何字段选择,所以将几个调用链接在一起会更简洁:

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

    或者甚至将字符串传递给sort

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

相关问题