QueryCursor
QueryCursor()
QueryCursor.prototype.addCursorFlag()
QueryCursor.prototype.close()
QueryCursor.prototype.eachAsync()
QueryCursor.prototype.getDriverCursor()
QueryCursor.prototype.map()
QueryCursor.prototype.next()
QueryCursor.prototype.options
QueryCursor.prototype.rewind()
QueryCursor.prototype[Symbol.asyncIterator]()
QueryCursor()
參數 (Parameters)
query
«Query»options
«Object» 傳遞給.find()
的查詢選項
繼承
QueryCursor 是一個並行處理基本元件,用於一次處理一個查詢結果文件。QueryCursor 除了提供其他機制可從 MongoDB 一次載入一個文件外,還實現了 Node.js streams3 API。
QueryCursor 會在從 MongoDB 載入任何文件之前執行模型的 find
前置鉤子 (pre find hooks),並在載入每個文件後執行模型的 find
後置鉤子 (post find hooks)。
除非您是進階使用者,否則請勿直接實例化此類別。請改用 Query#cursor()
。
QueryCursor.prototype.addCursorFlag()
參數 (Parameters)
flag
«String»value
«Boolean»
回傳
- «AggregationCursor» this
新增一個 游標旗標。適用於設定 noCursorTimeout
和 tailable
旗標。
QueryCursor.prototype.close()
回傳
- «Promise»
請參閱
將此游標標記為已關閉。將停止串流,後續對 next()
的呼叫將會產生錯誤。
QueryCursor.prototype.eachAsync()
參數 (Parameters)
fn
«Function»[options]
«Object»[options.parallel]
«Number» 平行執行的 Promise 數量。預設值為 1。[options.batchSize]
«Number» 如果設定,將會使用最多batchSize
長度的文件陣列呼叫fn()
。[options.continueOnError=false]
«Boolean» 如果為 true,即使fn
擲回錯誤,eachAsync()
也會迭代所有文件。如果為 false,如果給定的函數fn()
擲回錯誤,eachAsync()
會立即擲回錯誤。
回傳
- «Promise»
針對游標中的每個文件執行 fn
。如果 fn
回傳 Promise,則在迭代到下一個文件之前,會等待 Promise 解析完成。回傳一個在完成時解析的 Promise。
範例
// Iterate over documents asynchronously
Thing.
find({ name: /^hello/ }).
cursor().
eachAsync(async function (doc, i) {
doc.foo = doc.bar + i;
await doc.save();
})
QueryCursor.prototype.getDriverCursor()
回傳此游標使用的 MongoDB Node 驅動程式的底層游標。
QueryCursor.prototype.map()
參數 (Parameters)
fn
«Function»
回傳
- «QueryCursor»
註冊一個轉換函數,該函數後續會對透過串流介面或 .next()
擷取的文件進行映射。
範例
// Map documents returned by `data` events
Thing.
find({ name: /^hello/ }).
cursor().
map(function (doc) {
doc.foo = "bar";
return doc;
})
on('data', function(doc) { console.log(doc.foo); });
// Or map documents returned by `.next()`
const cursor = Thing.find({ name: /^hello/ }).
cursor().
map(function (doc) {
doc.foo = "bar";
return doc;
});
cursor.next(function(error, doc) {
console.log(doc.foo);
});
QueryCursor.prototype.next()
回傳
- «Promise»
從此游標取得下一個文件。當沒有剩餘文件時,將回傳 null
。
QueryCursor.prototype.options
類型
- «property»
傳遞至 QueryCursor
建構函式的 options
。
QueryCursor.prototype.rewind()
回傳
- «AggregationCursor» this
將此游標倒轉回未初始化的狀態。游標上存在的任何選項將保持有效。迭代此游標將會導致向伺服器傳送新的查詢,即使此游標已擷取結果資料。
QueryCursor.prototype[Symbol.asyncIterator]()
回傳一個 asyncIterator,用於 for/await/of
迴圈。您不需要明確呼叫此函數,JavaScript 執行階段會為您呼叫。
範例
// Works without using `cursor()`
for await (const doc of Model.find([{ $sort: { name: 1 } }])) {
console.log(doc.name);
}
// Can also use `cursor()`
for await (const doc of Model.find([{ $sort: { name: 1 } }]).cursor()) {
console.log(doc.name);
}
Node.js 10.x 原生支援非同步迭代器,無需任何旗標。您可以使用 --harmony_async_iteration
旗標 在 Node.js 8.x 中啟用非同步迭代器。
注意:如果 Symbol.asyncIterator
未定義,則此函數不是。如果 Symbol.asyncIterator
未定義,則表示您的 Node.js 版本不支援非同步迭代器。