我找不到关于排序修饰符的文档。唯一的线索在于单元测试中: spec.lib.query.js#L12
writer.limit(5).sort(['test', 1]).group('name')
但对我来说不起作用:
Post.find().sort(['updatedAt', 1]);
我找不到关于排序修饰符的文档。唯一的线索在于单元测试中: spec.lib.query.js#L12
writer.limit(5).sort(['test', 1]).group('name')
但对我来说不起作用:
Post.find().sort(['updatedAt', 1]);
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) { ... });
{sort: [['date', 1]]}
将不能正常工作,但是.sort([['date', -1]])
可以正常工作。请参考这个回答:https://dev59.com/Dm025IYBdhLWcg3wvIq2#15081087 - steampowered1
和-1
值的含义,而不是只有4行代码,没有太多上下文。 - Philipp以下是我在mongoose 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
})
Array
进行字段选择 - 必须使用String
或Object
。 - Philipp Kyeck截至Mongoose 3.8.x版本:
model.find({ ... }).sort({ field : criteria}).exec(function(err, model){ ... });
位置:
criteria
可以是 asc
、desc
、ascending
、descending
、1
或 -1
注:请使用引号或双引号
使用 "asc"
、"desc"
、"ascending"
、"descending"
、1
或 -1
更新:
Post.find().sort({'updatedAt': -1}).all((posts) => {
// do something with the array of posts
});
尝试:Post.find().sort([['updatedAt', 'descending']]).all((posts) => {
// do something with the array of posts
});
.sort("updatedAt", -1)
。 - Marcel Jackwerth.sort({updatedAt: -1})
或 .sort('-updatedAt')
可以进行排序。 - Andreas Hultgrenexec(function (posts) {…
而不是 all
。 - Buzutall() must be used after where() when called with these arguments
的错误。 - Dam FaPost.find().sort({updatedAt: -1}).all((posts) => {
- dipakbari4Mongoose v5.x.x
按升序排序
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) { ... });
按照降序排序
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) { ... });
Post.find({}, null, {sort: '-field'}, function(err, docs) { ... });
可以用于降序查询,而 Post.find({}, null, {sort: 'field'}, function(err, docs) { ... });
则可以用于升序查询。事实上,由于我将字段和排序顺序作为 HTTP 查询参数传递,将它们组合成一个字符串并使用这种方式对我的数据库查询进行排序是唯一的选择。 - Vincenzo更新
如果这篇文章让人感到困惑,可以查看mongoose手册中的查找文档和查询工作原理,那里有更好的解释。如果你想使用流畅的API,可以通过不提供find()
方法的回调来获得一个查询对象,否则你可以按照我下面的说明来指定参数。
原始内容
根据模型文档中对model
对象的描述,对于版本2.4.1
,它可以起作用的方式如下:
Post.find({search-spec}, [return field array], {options}, callback)
搜索规范(search spec
)需要一个对象,但你可以传递null
或一个空对象。
第二个参数是字段列表,作为字符串数组。例如,你应该使用['field','field2']
或null
。
第三个参数是选项,作为一个对象,其中包括对结果集进行排序的能力。你将使用{ sort: { field: direction } }
,其中field
是字段名 test
的字符串(在你的情况下),而direction
则是一个数字,其中1
表示升序,-1
表示降序。
最后一个参数(callback
)是回调函数,用于接收查询返回的文档集合。
Model.find()
实现(在此版本中)使用滑动分配属性来处理可选参数(这就是让我困惑的地方!):
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
您可以通过以下方式对查询结果进行排序:
Post.find().sort({createdAt: "descending"});
以下是我如何在 mongoose.js 2.0.4 中使用排序的方法
var query = EmailModel.find({domain:"gmail.com"});
query.sort('priority', 1);
query.exec(function(error, docs){
//...
});
// 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
})
有关查询的更多信息,请参见文档。
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)
})
})
输出
[ { _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 } ]