Ich finde kein doc für den Sortiermodifikator. Die einzige Einsicht besteht in den Unit-Tests: spec.lib.query.js # L12
writer.limit(5).sort(['test', 1]).group('name')
Aber es funktioniert nicht für mich:
Post.find().sort(['updatedAt', 1]);
So habe ich in mongoose 2.3.0 arbeiten können :)
// 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
})
In Mongoose kann eine Sortierung auf eine der folgenden Arten erfolgen:
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) { ... });
Versuchen:
Post.find().sort([['updatedAt', 'descending']]).all(function (posts) {
// do something with the array of posts
});
Ab Mongoose 3.8.x:
model.find({ ... }).sort({ field : criteria}).exec(function(err, model){ ... });
Woher:
criteria
kann asc
, desc
, ascending
, descending
, 1
oder -1
sein
Update
Es gibt ein besseres Schreiben, wenn dies die Leute verwirrt; Auschecken Dokumente finden und wie Abfragen funktionieren im Moose-Manual. Wenn Sie die fließende API verwenden möchten, können Sie ein Abfrageobjekt abrufen, indem Sie der find()
-Methode keinen Rückruf bereitstellen. Andernfalls können Sie die Parameter wie in der nachstehenden Beschreibung angegeben angeben.
Original
Bei einem model
-Objekt kann dies anhand der docs in Model auf folgende Weise für 2.4.1
ausgeführt werden:
Post.find({search-spec}, [return field array], {options}, callback)
Der search spec
erwartet ein Objekt, Sie können jedoch null
oder ein leeres Objekt übergeben.
Der zweite Parameter ist die Feldliste als ein String-Array, also würden Sie ['field','field2']
oder null
angeben.
Der dritte Parameter sind die Optionen als Objekt, das die Möglichkeit enthält, die Ergebnismenge zu sortieren. Sie würden { sort: { field: direction } }
verwenden, wobei field
der String Feldname test
ist (in Ihrem Fall) und direction
eine Zahl ist, bei der 1
aufsteigend ist und -1
absteigt.
Der letzte Parameter (callback
) ist die Rückruffunktion, die die von der Abfrage zurückgegebene Sammlung von Dokumenten empfängt.
Die Model.find()
-Implementierung (bei dieser Version) führt eine gleitende Zuordnung von Eigenschaften aus, um optionale Parameter zu behandeln (was mich verwirrt hat!):
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
So habe ich in mongoose.js 2.0.4 arbeiten können
var query = EmailModel.find({domain:"gmail.com"});
query.sort('priority', 1);
query.exec(function(error, docs){
//...
});
Verkettung mit der Abfrageerstellungsschnittstelle in 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
})
Weitere Informationen zu Abfragen finden Sie unter docs .
wenn Sie mit der aktuellen Version von mongoose (1.6.0) nur die Spalte one sortieren möchten, müssen Sie das Array löschen und das Objekt direkt an die sort () - Funktion übergeben:
Content.find().sort('created', 'descending').execFind( ... );
ich habe einige Zeit gebraucht, um das richtig zu machen :(
So habe ich es geschafft zu sortieren und zu bevölkern:
Model.find()
.sort('date', -1)
.populate('authors')
.exec(function(err, docs) {
// code here
})
Post.find().sort({updatedAt: 1});
Andere arbeiteten für mich, aber dies tat:
Tag.find().sort('name', 1).run(onComplete);
Mongoose v5.4.3
aufsteigend sortieren
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) { ... });
nach absteigender Reihenfolge sortieren
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) { ... });
Für Details: https://mongoosejs.com/docs/api.html#query_Query-sort
Post.find().sort({updatedAt:1}).exec(function (err, posts){
...
});
Dies ist, was ich getan habe, es funktioniert gut.
User.find({name:'Thava'}, null, {sort: { name : 1 }})
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)
})
})
====================================
AUSGABE------------------------------------------------- -------------------------------
[ { _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 } ]