在猫鼬中,我如何按日期排序?(节点.js) [英] In Mongoose, how do I sort by date? (node.js)

查看:27
本文介绍了在猫鼬中,我如何按日期排序?(节点.js)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在 Mongoose 中运行此查询:

let's say I run this query in Mongoose:

    Room.find({}, (err,docs) => {
    
    }).sort({date:-1}); 

这不起作用!

推荐答案

排序 在 Mongoose 中随着版本的不断发展,其中一些答案不再有效.从 Mongoose 的 4.1.x 版本开始,可以通过以下任一方式对 date 字段进行降序排序:

Sorting in Mongoose has evolved over the releases such that some of these answers are no longer valid. As of the 4.1.x release of Mongoose, a descending sort on the date field can be done in any of the following ways:

    Room.find({}).sort('-date').exec((err, docs) => { ... });
    Room.find({}).sort({date: -1}).exec((err, docs) => { ... });
    Room.find({}).sort({date: 'desc'}).exec((err, docs) => { ... });
    Room.find({}).sort({date: 'descending'}).exec((err, docs) => { ... });
    Room.find({}).sort([['date', -1]]).exec((err, docs) => { ... });
    Room.find({}, null, {sort: '-date'}, (err, docs) => { ... });
    Room.find({}, null, {sort: {date: -1}}, (err, docs) => { ... });

对于升序排序,省略字符串版本上的 - 前缀或使用 1ascascending 的值.

For an ascending sort, omit the - prefix on the string version or use values of 1, asc, or ascending.

这篇关于在猫鼬中,我如何按日期排序?(节点.js)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆