gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:54:58 25 4
gpt4 key购买 nike

基本问题

我有一堆记录,我需要获取最新的(最近的)和最旧的(最近的)。

谷歌搜索时我发现 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.

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

时间跨度

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

这是架构:

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 中的 [] 参数调用,因为选择要包含的字段的参数不再支持数组格式。

试试这个来找到最新的:

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

关于javascript - 如何在 mongoose.js 中获取最新和最旧的记录(或者只是它们之间的时间跨度),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12467102/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com