Nodejs mongoose里对时间排序无法实现

Nodejs mongoose里对时间排序无法实现

posts.find().sort({“theDate:-1”}).exec(functions(err,posts){
});

无论是mongoose还是mongo shell都无法实现。 我要对时间排倒序,这是官方doc写的,但是无法实现。 StackOverFlow上的部分解决方法现已不可用。 提示:sort方法只能传String或者Object。

5 回复

当然可以!让我们来看一下如何在 Mongoose 中正确地对时间进行排序。根据你提供的信息,问题可能在于 sort 方法的参数格式不正确。Mongoose 的 sort 方法需要一个对象作为参数,而不是字符串。

示例代码

假设我们有一个 Post 模型,并且该模型有一个名为 theDate 的日期字段。以下是如何正确地按 theDate 字段进行降序排序的示例代码:

const mongoose = require('mongoose');
const Post = mongoose.model('Post', new mongoose.Schema({
    theDate: Date
}));

// 正确的 sort 方法使用对象作为参数
Post.find()
    .sort({ theDate: -1 }) // -1 表示降序排序
    .exec((err, posts) => {
        if (err) {
            console.error('Error:', err);
            return;
        }
        console.log('Sorted Posts:', posts);
    });

解释

  1. 定义模型

    const Post = mongoose.model('Post', new mongoose.Schema({
        theDate: Date
    }));
    

    这里定义了一个 Post 模型,其中包含一个 theDate 字段,类型为 Date

  2. 查询并排序

    Post.find()
        .sort({ theDate: -1 })
        .exec((err, posts) => {
            if (err) {
                console.error('Error:', err);
                return;
            }
            console.log('Sorted Posts:', posts);
        });
    
    • Post.find():查询所有文档。
    • .sort({ theDate: -1 }):对 theDate 字段进行降序排序。-1 表示降序,1 表示升序。
    • .exec(...):执行查询并传递回调函数处理结果或错误。

注意事项

  • 确保 theDate 字段存在于你的数据库中,并且数据类型为 Date
  • 确保你已经正确连接到 MongoDB 数据库,并且 Mongoose 已经初始化。

通过这种方式,你可以轻松地在 Mongoose 中按时间字段进行排序。希望这能解决你的问题!


我觉得是 { 'theDate' : -1 }

我们所有的时间全部用的时间戳 都是数字

所以没有这问题。。。

同意:{“theDate:-1”} 就是个字符串

$ node
> {"theDate:-1"}
'theDate:-1'

根据你提供的代码片段,问题出在 sort 方法的参数格式上。sort 方法期望一个对象作为参数,而不是一个字符串。正确的格式应该是一个对象,其中键是字段名,值是指定的排序顺序(例如 1 表示升序,-1 表示降序)。

以下是修正后的示例代码:

posts.find().sort({ theDate: -1 }).exec(function (err, posts) {
    if (err) {
        console.error("Error fetching posts:", err);
        return;
    }
    console.log(posts);
});

解释:

  • sort({ theDate: -1 }):这表示按 theDate 字段进行降序排序。
  • exec 回调函数中处理结果和错误。

确保 theDate 字段在你的 Mongoose 模型中是一个日期类型,并且名称拼写正确。如果仍然有问题,请检查数据库中的数据是否包含有效的日期字段。

回到顶部