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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12467102/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 08:02:15  来源:igfitidea点击:

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

javascriptnode.jsmongoosetimespan

提问by askmike

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 topicwhere I saw a couple of queries:

在谷歌搜索时,我发现了这个话题,我看到了几个查询:

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

Unfortunatly they both error:

不幸的是,他们都错误:

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

The link also has this one:

链接也有这个:

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

and that one errors:

还有一个错误:

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

So how can I get those records?

那么我怎样才能得到这些记录呢?

Timespan

时间跨度

Even more ideally I just want the difference in time (seconds?) between the oldest and the newest record, but I have no clue on how to start making a query like that.

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

This is the schema:

这是架构:

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

I'm pretty sure I have the most recent version of mongoDB and mongoose.

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

EDIT

编辑

This is how I calc the timespan based on the answer provided by JohnnyHK:

这是我根据 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 );
    }
  );
}

回答by JohnnyHK

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

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

Try this instead to find the newest:

试试这个来找到最新的:

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

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

将 更改-1为 a1以查找最旧的。

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:

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

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

回答by WasiF

Tested on mongoose 5.4.x

在猫鼬 5.4.x 上测试

Get 10 latest documents

得到 10 latest documents

MySchema.find().sort({ _id: -1 }).limit(10)

Get 10 oldest documents

得到 10 oldest documents

MySchema.find().sort({ _id: 1 }).limit(10)

回答by atom2ueki

for version ~3.8 mongoose

对于版本 ~3.8 猫鼬

to find the last entry

找到最后一个条目

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

or using

或使用

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

回答by Fabio do Nascimento

collectionName.findOne().sort({$natural: -1}).limit(1).exec(function(err, res){
    if(err){
        console.log(err);
    }
    else{
        console.log(res);
    }
}

This will give you the last document recorded on the database. Just follow the same concept.

这将为您提供数据库中记录的最后一个文档。只需遵循相同的概念。

回答by KARTHIKEYAN.A

We have method called sort using that we can able to get first element(old document) which means 1 for sort fieldor last element(new document) which means -1 for sort fieldof collection.

我们有一个叫做 sort 的方法,我们可以使用它来获取第一个元素(旧文档),这意味着排序字段为 1最后一个元素(新文档),这意味着集合的排序字段-1