如何获取mongoose.js中最新和最旧的logging(或者只是它们之间的时间跨度)

基本问题

我有一堆logging,我需要得到最新(最近)和最旧(最近)。

当谷歌search时,我发现这个话题 ,我看到了几个查询:

// 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. 

那么我怎么能得到这些logging呢?

时间跨度

更理想的是,我只是想要在最早的和最新的logging之间的时间差(秒?),但我不知道如何开始做这样的查询。

这是架构:

 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提供的答案来计算时间跨度:

 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 ); } ); } 

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

试试这个,而不是find最新的:

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

-1更改为1以查找最老的。

但是因为你没有使用任何字段select,所以把几个电话联系在一起会更清楚:

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

甚至传递一个string来sort

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

版本〜3.8mongoose

find最后一个条目

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

或使用

 model.findOne().sort({ field: -_id }).limit(1) 
Interesting Posts