Meteor排序

只要我們能從數據庫中獲取數據,就可以拿它們來進行排序。在這個例子中,我們將創建一個用戶(Users)集合。我們使用排序參數 ({sort: {name: 1}}) 按名稱排序集合數據。數值1 是用來設置升序排列。如果我們要從大到小的順序,那麼使用數值 -1 代替。

Users = new Mongo.Collection('users');

Users.insert({
name: 'James',
email: '[email protected]',
joined: new Date(2016, 2, 23)
});

Users.insert({
name: 'John',
email: '[email protected]',
joined: new Date(2016, 2, 19)
});

Users.insert({
name: 'Jennifer',
email: '[email protected]',
joined: new Date(2016, 6, 24)
});

var sortByName = Users.find({}, {sort: {name: 1}}).fetch();

var sortByEmail = Users.find({}, {sort: {email: 1}}).fetch();

var sortByJoined = Users.find({}, {sort: {joined: 1}}).fetch();

console.log(sortByName);
console.log(sortByEmail);
console.log(sortByJoined);

Meteor排序

我們可以通過電子郵件的數據以相同的方式進行排序。

Users = new Mongo.Collection('users');

Users.insert({
name: 'James',
email: '[email protected]',
joined: new Date(2016, 2, 23)
});

Users.insert({
name: 'John',
email: '[email protected]',
joined: new Date(2016, 2, 19)
});

Users.insert({
name: 'Jennifer',
email: '[email protected]',
joined: new Date(2016, 6, 24)
});

var sortByEmail = Users.find({}, {sort: {email: 1}}).fetch();

console.log(sortByEmail);

Meteor排序

最後,我們可以通過加入日期來排序。

Users = new Mongo.Collection('users');

Users.insert({
name: 'James',
email: '[email protected]',
joined: new Date(2016, 2, 23)
});

Users.insert({
name: 'John',
email: '[email protected]',
joined: new Date(2016, 2, 19)
});

Users.insert({
name: 'Jennifer',
email: '[email protected]',
joined: new Date(2016, 6, 24)
});

var sortByJoined = Users.find({}, {sort: {joined: 1}}).fetch();

console.log(sortByJoined);

Meteor排序