查询

所有官方数据库适配器都支持查询, 排序, 限制和选择 find 方法调用的常用方法, 作为 params.query 的一部分. 如果将 id 设置为 null, 查询也会应用 update, patchremove 方法调用.

重要

通过REST URL使用时, 所有查询值都是字符串. 取决于服务的值 hooks.

Equality

不包含特殊查询参数的所有字段将直接进行相等性比较.

// Find all unread messages in room #2
app.service('messages').find({
  query: {
    read: false,
    roomId: 2
  }
});
GET /messages?read=false&roomId=2

$limit

$limit 将仅返回您指定的结果数:

// Retrieves the first two unread messages
app.service('messages').find({
  query: {
    $limit: 2,
    read: false
  }
});
GET /messages?$limit=2&read=false

小技巧

common#pagination. 只是得到可用记录的数量 $limit 设置为 0. 这只会对数据库运行一个(快速)计数查询, 并返回一个带有 total 和一个空 data 数组的页面对象.

$sort

$sort 将根据您提供的对象进行排序. 它可以包含一个属性列表, 通过它可以排序映射到顺序(1 升序, -1 降序).

// Find the 10 newest messages
app.service('messages').find({
  query: {
    $limit: 10,
    $sort: {
      createdAt: -1
    }
  }
});
/messages?$limit=10&$sort[createdAt]=-1

$select

$select 允许选择要包含在结果中的字段. 这适用于任何服务方法.

// Only return the `text` and `userId` field in a message
app.service('messages').find({
  query: {
    $select: [ 'text', 'userId' ]
  }
});

app.service('messages').get(1, {
  query: {
    $select: [ 'text' ]
  }
});
GET /messages?$select[]=text&$select[]=userId
GET /messages/1?$select[]=text

$in, $nin

找到属性所做的所有记录($in)或不匹配任何给定值($nin).

// Find all messages in room 2 or 5
app.service('messages').find({
  query: {
    roomId: {
      $in: [ 2, 5 ]
    }
  }
});
GET /messages?roomId[$in]=2&roomId[$in]=5

$lt, $lte

查找值较小(“$lt``”)或更少且等于($lte)到给定值的所有记录.

// Find all messages older than a day
const DAY_MS = 24 * 60 * 60 * 1000;

app.service('messages').find({
  query: {
    createdAt: {
      $lt: new Date().getTime() - DAY_MS
    }
  }
});
GET /messages?createdAt[$lt]=1479664146607

$gt, $gte

查找值为更多($gt)或更多且等于($gte)到给定值的所有记录.

// Find all messages within the last day
const DAY_MS = 24 * 60 * 60 * 1000;

app.service('messages').find({
  query: {
    createdAt: {
      $gt: new Date().getTime() - DAY_MS
    }
  }
});
GET /messages?createdAt[$gt]=1479664146607

$ne

查找不等于给定属性值的所有记录.

// Find all messages that are not marked as archived
app.service('messages').find({
  query: {
    archived: {
      $ne: true
    }
  }
});
GET /messages?archived[$ne]=true

$or

查找符合任何给定条件的所有记录.

// Find all messages that are not marked as archived
// or any message from room 2
app.service('messages').find({
  query: {
    $or: [
      { archived: { $ne: true } },
      { roomId: 2 }
    ]
  }
});
GET /messages?$or[0][archived][$ne]=true&$or[1][roomId]=2