如何在 mongoose.js 中获取最新和最旧的记录(或者只是它们之间的时间跨度) [英] How to get the latest and oldest record in mongoose.js (or just the timespan between them)
问题描述
我有一堆记录,我需要获取最新的(最近的)和最旧的(最近的).
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 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 );
});
不幸的是他们都错了:
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.
那么我如何获得这些记录?
So how can I get those records?
更理想的是,我只想要最旧和最新记录之间的时间差(秒?),但我不知道如何开始进行这样的查询.
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.
这是架构:
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.
I'm pretty sure I have the most recent version of mongoDB and mongoose.
这是我根据 JohnnyHK 提供的答案计算时间跨度的方式:
This is how I calc the timespan based on the answer provided by 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
调用,因为选择要包含的字段的参数不再支持数组格式.
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 );
});
将 -1
更改为 1
以查找最旧的.
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) { ... });
或者甚至将字符串传递给 sort
:
Or even pass a string to sort
:
Tweet.findOne().sort('-created_at').exec(function(err, post) { ... });
这篇关于如何在 mongoose.js 中获取最新和最旧的记录(或者只是它们之间的时间跨度)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!