天天看點

orm2 中文文檔 6. 查找記錄

譯者: 飛龍 來源: Finding items

find

查找比對标準的記錄,可以鍊式查詢(見下文):

Person.find({status:'active'}, function(err, results) {
  // ...
});           

你也可以限制結果的個數,這條語句限制結果為10個:

Person.find({status:'active'}, 10, function(err, results) {
  // ...
});           

Person.all

Person.find

的别名。

get

通過主鍵來查找記錄。

Person.get(1, function(err, person) {
  // ...
});           

one

隻查找一個記錄,和

find

的文法相似。

Person.one({status:'active'}, function(err, person) {
  // ...
});           

count

擷取所比對記錄的數量。

Person.count({status:'active'}, function(err, activePeopleCount) {
  // ...
});           

exists

測試比對你的條件的記錄是否存在。

Person.exists({id:1, status:'active'}, function(err, personIsActive) {
  // ...
});           

過濾和排序

我們接受兩個對象來執行過濾(第一個)和聚合(第二個)。聚合對象接受

limit

order

groupBy

https://github.com/dresende/node-orm2/blob/v2.1.20/lib/AggregateFunctions.js#L36
Person.find({status:'active'}, {limit:10}, function(err, res) {

});           

find

/

count

one

等方法的條件查詢

所有以逗号分隔的鍵值對在查詢中都會以

AND

連接配接。你可以把邏輯運算符放在一系列條件的前面。

Person.find({or:[{col1: 1}, {col2: 2}]}, function(err, res) {
  // res 為 col1 == 1 或者 col2 == 2 的 Person
});           

使用

IN

來查找

sql-query

(取決于SQL引擎)會自動将數組視為基于

IN

的查詢。

https://github.com/dresende/node-sql-query/blob/v0.1.23/lib/Where.js#L172
Person.find({id: [1, 2]}, function(err, persons) {
  // 查找 id 是 1 或者 2 的 Person (例如 WHERE id IN (1, 2) )
});