Как сортировать в мангусте? - программирование
Подтвердить что ты не робот

Как сортировать в мангусте?

Я не нахожу документацию по модификатору сортировки. Единственное понимание - в модульных тестах: spec.lib.query.js # L12

writer.limit(5).sort(['test', 1]).group('name')

Но это не работает для меня:

Post.find().sort(['updatedAt', 1]);
4b9b3361

Ответ 1

Вот как я получил сортировку для работы в 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
})

Ответ 2

В 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) { ... });

Ответ 3

По состоянию на Mongoose 3.8.x:

model.find({ ... }).sort({ field : criteria}).exec(function(err, model){ ... });

Где:

criteria может быть asc, desc, ascending, descending, 1 или -1

Ответ 4

Try:

Post.find().sort([['updatedAt', 'descending']]).all(function (posts) {
  // do something with the array of posts
});

Ответ 5

Обновление

Лучше писать, если это путает людей; найти документы и как работают запросы в руководстве для мангуста, Если вы хотите использовать свободный api, вы можете получить объект запроса, не предоставляя обратный вызов методу find(), иначе вы можете указать параметры, как я опишу ниже.

Оригинал

Для объекта model, для docs в Model, так оно может работать для 2.4.1:

Post.find({search-spec}, [return field array], {options}, callback)

search spec ожидает объект, но вы можете передать null или пустой объект.

Второй параметр - это список полей в виде массива строк, поэтому вы должны поставить ['field','field2'] или null.

Третий параметр - это параметры как объект, который включает в себя возможность сортировки набора результатов. Вы должны использовать { sort: { field: direction } }, где field - это имя поля string 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);
};

НТН

Ответ 6

Mongoose v5.4.3

сортировать по возрастанию

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) { ... });

Для подробностей: https://mongoosejs.com/docs/api.html#query_Query-sort

Ответ 7

Вот как я получил сортировку для работы в mongoose.js 2.0.4

var query = EmailModel.find({domain:"gmail.com"});
query.sort('priority', 1);
query.exec(function(error, docs){
  //...
});

Ответ 8

Связывание с интерфейсом построителя запросов в 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
})

Смотрите документы для получения дополнительной информации о запросах.

Ответ 9

с текущей версией mongoose (1.6.0), если вы хотите отсортировать только столбец один, вам нужно отбросить массив и передать объект непосредственно функции sort():

Content.find().sort('created', 'descending').execFind( ... );

взял меня на некоторое время, чтобы получить это право: (

Ответ 10

Вот как мне удалось сортировать и заполнять:

Model.find()
.sort('date', -1)
.populate('authors')
.exec(function(err, docs) {
    // code here
})

Ответ 11

Другие работали для меня, но это делало:

  Tag.find().sort('name', 1).run(onComplete);

Ответ 12

Post.find().sort({updatedAt: 1});

Ответ 13

Post.find().sort({updatedAt:1}).exec(function (err, posts){
...
});

Ответ 14

Это то, что я сделал, работает отлично.

User.find({name:'Thava'}, null, {sort: { name : 1 }})

Ответ 15

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 } ]