node.js 如何在猫鼬中排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4299991/
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
How to sort in mongoose?
提问by Philippe Rathé
I find no doc for the sort modifier. The only insight is in the unit tests: spec.lib.query.js#L12
我没有找到排序修饰符的文档。唯一的见解是在单元测试中: spec.lib.query.js#L12
writer.limit(5).sort(['test', 1]).group('name')
But it doesn't work for me:
但这对我不起作用:
Post.find().sort(['updatedAt', 1]);
回答by iwein
In Mongoose, a sort can be done in any of the following ways:
在 Mongoose 中,可以通过以下任何一种方式进行排序:
Post.find({}).sort('test').exec(function(err, docs) { ... });
Post.find({}).sort([['date', -1]]).exec(function(err, docs) { ... });
Post.find({}).sort({test: 1}).exec(function(err, docs) { ... });
Post.find({}, null, {sort: {date: 1}}, function(err, docs) { ... });
回答by Derek Bredensteiner
This is how I got sort to work in mongoose 2.3.0 :)
这就是我在猫鼬 2.3.0 中工作的方式:)
// Find First 10 News Items
News.find({
deal_id:deal._id // Search Filters
},
['type','date_added'], // Columns to Return
{
skip:0, // Starting Row
limit:10, // Ending Row
sort:{
date_added: -1 //Sort by Date Added DESC
}
},
function(err,allNews){
socket.emit('news-load', allNews); // Do something with the array of 10 objects
})
回答by user3784764
As of Mongoose 3.8.x:
从猫鼬 3.8.x 开始:
model.find({ ... }).sort({ field : criteria}).exec(function(err, model){ ... });
Where:
在哪里:
criteriacan be asc, desc, ascending, descending, 1, or -1
criteria可以是asc, desc, ascending, descending, 1, 或-1
回答by Eric
Try:
尝试:
Post.find().sort([['updatedAt', 'descending']]).all(function (posts) {
// do something with the array of posts
});
回答by AJ.
Update
更新
There is a better write up if this is confusing people; check out finding documentsand how queries workin the mongoose manual. If you want to use the fluent api you can get a query object by not providing a callback to the find()method, otherwise you can specify the parameters as I outline below.
如果这让人们感到困惑,还有更好的写法;在 mongoose 手册中查看查找文档以及查询如何工作。如果您想使用 fluent api,您可以通过不向该find()方法提供回调来获取查询对象,否则您可以指定我在下面概述的参数。
Original
原来的
Given a modelobject, per the docs on Model, this is how it can work for 2.4.1:
给定一个model对象,根据Model 上的文档,它是如何工作的2.4.1:
Post.find({search-spec}, [return field array], {options}, callback)
The search specexpects an object, but you can pass nullor an empty object.
该search spec预期的目标,但你可以通过null或空对象。
The second param is the field list as an array of strings, so you would supply ['field','field2']or null.
第二个参数是作为字符串数组的字段列表,因此您可以提供['field','field2']or null。
The third param is the options as an object, which includes the ability to sort the result set. You would use { sort: { field: direction } }where fieldis the string fieldname test(in your case) and directionis a number where 1is ascending and -1is desceding.
第三个参数是作为对象的选项,它包括对结果集进行排序的能力。您将使用{ sort: { field: direction } }wherefield是字符串字段名test(在您的情况下),direction是一个数字,其中1升序和-1降序。
The final param (callback) is the callback function which receives the collection of docs returned by the query.
最后一个参数 ( callback) 是回调函数,它接收查询返回的文档集合。
The Model.find()implementation (at this version) does a sliding allocation of properties to handle optional params (which is what confused me!):
在Model.find()实现(在这个版本)确实性质来处理可选则params的滑动分配(这是困惑我!):
Model.find = function find (conditions, fields, options, callback) {
if ('function' == typeof conditions) {
callback = conditions;
conditions = {};
fields = null;
options = null;
} else if ('function' == typeof fields) {
callback = fields;
fields = null;
options = null;
} else if ('function' == typeof options) {
callback = options;
options = null;
}
var query = new Query(conditions, options).select(fields).bind(this, 'find');
if ('undefined' === typeof callback)
return query;
this._applyNamedScope(query);
return query.find(callback);
};
HTH
HTH
回答by sultan aslam
Mongoose v5.4.3
猫鼬 v5.4.3
sort by ascending order
按升序排序
Post.find({}).sort('field').exec(function(err, docs) { ... });
Post.find({}).sort({ field: 'asc' }).exec(function(err, docs) { ... });
Post.find({}).sort({ field: 'ascending' }).exec(function(err, docs) { ... });
Post.find({}).sort({ field: 1 }).exec(function(err, docs) { ... });
Post.find({}, null, {sort: { field : 'asc' }}), function(err, docs) { ... });
Post.find({}, null, {sort: { field : 'ascending' }}), function(err, docs) { ... });
Post.find({}, null, {sort: { field : 1 }}), function(err, docs) { ... });
sort by descending order
按降序排序
Post.find({}).sort('-field').exec(function(err, docs) { ... });
Post.find({}).sort({ field: 'desc' }).exec(function(err, docs) { ... });
Post.find({}).sort({ field: 'descending' }).exec(function(err, docs) { ... });
Post.find({}).sort({ field: -1 }).exec(function(err, docs) { ... });
Post.find({}, null, {sort: { field : 'desc' }}), function(err, docs) { ... });
Post.find({}, null, {sort: { field : 'descending' }}), function(err, docs) { ... });
Post.find({}, null, {sort: { field : -1 }}), function(err, docs) { ... });
For Details: https://mongoosejs.com/docs/api.html#query_Query-sort
回答by Salida Software
This is how I got sort to work in mongoose.js 2.0.4
这就是我在 mongoose.js 2.0.4 中工作的方式
var query = EmailModel.find({domain:"gmail.com"});
query.sort('priority', 1);
query.exec(function(error, docs){
//...
});
回答by Salida Software
Chaining with the query builder interface in Mongoose 4.
与 Mongoose 4 中的查询构建器接口链接。
// Build up a query using chaining syntax. Since no callback is passed this will create an instance of Query.
var query = Person.
find({ occupation: /host/ }).
where('name.last').equals('Ghost'). // find each Person with a last name matching 'Ghost'
where('age').gt(17).lt(66).
where('likes').in(['vaporizing', 'talking']).
limit(10).
sort('-occupation'). // sort by occupation in decreasing order
select('name occupation'); // selecting the `name` and `occupation` fields
// Excute the query at a later time.
query.exec(function (err, person) {
if (err) return handleError(err);
console.log('%s %s is a %s.', person.name.first, person.name.last, person.occupation) // Space Ghost is a talk show host
})
See the docsfor more about queries.
有关查询的更多信息,请参阅文档。
回答by koteswararao pv
app.get('/getting',function(req,res){
Blog.find({}).limit(4).skip(2).sort({age:-1}).then((resu)=>{
res.send(resu);
console.log(resu)
// console.log(result)
})
})
Output
输出
[ { _id: 5c2eec3b8d6e5c20ed2f040e, name: 'e', age: 5, __v: 0 },
{ _id: 5c2eec0c8d6e5c20ed2f040d, name: 'd', age: 4, __v: 0 },
{ _id: 5c2eec048d6e5c20ed2f040c, name: 'c', age: 3, __v: 0 },
{ _id: 5c2eebf48d6e5c20ed2f040b, name: 'b', age: 2, __v: 0 } ]
回答by pkyeck
with the current version of mongoose (1.6.0) if you only want to sort by onecolumn, you have to drop the array and pass the object directly to the sort() function:
使用当前版本的 mongoose (1.6.0) 如果您只想按一列排序,则必须删除数组并将对象直接传递给 sort() 函数:
Content.find().sort('created', 'descending').execFind( ... );
took me some time, to get this right :(
我花了一些时间来解决这个问题:(

