查詢(Query)
Query()
Query.prototype.$where()
Query.prototype.all()
Query.prototype.allowDiskUse()
Query.prototype.and()
Query.prototype.batchSize()
Query.prototype.box()
Query.prototype.cast()
Query.prototype.catch()
Query.prototype.center()
Query.prototype.centerSphere()
Query.prototype.circle()
Query.prototype.clone()
Query.prototype.collation()
Query.prototype.comment()
Query.prototype.countDocuments()
Query.prototype.cursor()
Query.prototype.deleteMany()
Query.prototype.deleteOne()
Query.prototype.distinct()
Query.prototype.elemMatch()
Query.prototype.equals()
Query.prototype.error()
Query.prototype.estimatedDocumentCount()
Query.prototype.exec()
Query.prototype.exists()
Query.prototype.explain()
Query.prototype.finally()
Query.prototype.find()
Query.prototype.findOne()
Query.prototype.findOneAndDelete()
Query.prototype.findOneAndReplace()
Query.prototype.findOneAndUpdate()
Query.prototype.geometry()
Query.prototype.get()
Query.prototype.getFilter()
Query.prototype.getOptions()
Query.prototype.getPopulatedPaths()
Query.prototype.getQuery()
Query.prototype.getUpdate()
Query.prototype.gt()
Query.prototype.gte()
Query.prototype.hint()
Query.prototype.in()
Query.prototype.intersects()
Query.prototype.isPathSelectedInclusive()
Query.prototype.j()
Query.prototype.lean()
Query.prototype.limit()
Query.prototype.lt()
Query.prototype.lte()
Query.prototype.maxDistance()
Query.prototype.maxTimeMS()
Query.prototype.merge()
Query.prototype.mod()
Query.prototype.model
Query.prototype.mongooseOptions()
Query.prototype.ne()
Query.prototype.near()
Query.prototype.nearSphere()
Query.prototype.nin()
Query.prototype.nor()
Query.prototype.or()
Query.prototype.orFail()
Query.prototype.polygon()
Query.prototype.populate()
Query.prototype.post()
Query.prototype.pre()
Query.prototype.projection()
Query.prototype.read()
Query.prototype.readConcern()
Query.prototype.regex()
Query.prototype.replaceOne()
Query.prototype.sanitizeProjection()
Query.prototype.select()
Query.prototype.selected()
Query.prototype.selectedExclusively()
Query.prototype.selectedInclusively()
Query.prototype.session()
Query.prototype.set()
Query.prototype.setOptions()
Query.prototype.setQuery()
Query.prototype.setUpdate()
Query.prototype.size()
Query.prototype.skip()
Query.prototype.slice()
Query.prototype.sort()
Query.prototype.tailable()
Query.prototype.then()
Query.prototype.toConstructor()
Query.prototype.transform()
Query.prototype.updateMany()
Query.prototype.updateOne()
Query.prototype.w()
Query.prototype.where()
Query.prototype.within()
Query.prototype.writeConcern()
Query.prototype.wtimeout()
Query.prototype[Symbol.asyncIterator]()
Query.prototype[Symbol.toStringTag]()
Query.use$geoWithin
Query()
參數
[options]
«物件»[model]
«物件»[conditions]
«物件»[collection]
«物件» Mongoose 集合
用於建立查詢的 Query 建構函式。您不需要直接實例化 Query
。而是使用模型函數,例如 Model.find()
。
範例
const query = MyModel.find(); // `query` is an instance of `Query`
query.setOptions({ lean : true });
query.collection(MyModel.collection);
query.where('age').gte(21).exec(callback);
// You can instantiate a query directly. There is no need to do
// this unless you're an advanced user with a very good reason to.
const query = new mongoose.Query();
Query.prototype.$where()
參數
js
«字串|函式» javascript 字串或函式
傳回
- «查詢» this
參見
指定要傳遞給 MongoDB 查詢系統的 javascript 函數或表達式。
範例
query.$where('this.comments.length === 10 || this.name.length === 5')
// or
query.$where(function () {
return this.comments.length === 10 || this.name.length === 5;
})
注意
只有在您有無法使用其他 MongoDB 運算符(例如 $lt
)滿足的條件時才使用 $where
。在使用之前,請務必閱讀關於其所有注意事項。
Query.prototype.all()
參數
[path]
«字串»val
«陣列»
參見
指定 $all
查詢條件。
當使用一個參數呼叫時,將使用傳遞給 where()
的最近路徑。
範例
MyModel.find().where('pets').all(['dog', 'cat', 'ferret']);
// Equivalent:
MyModel.find().all('pets', ['dog', 'cat', 'ferret']);
Query.prototype.allowDiskUse()
參數
[v]
«布林值» 啟用/停用allowDiskUse
。如果使用 0 個參數呼叫,則設定allowDiskUse: true
傳回
- «查詢» this
設定 allowDiskUse
選項,該選項允許 MongoDB 伺服器對此查詢的 sort()
使用超過 100 MB 的記憶體。此選項可讓您解決來自 MongoDB 伺服器的 QueryExceededMemoryLimitNoDiskUseAllowed
錯誤。
請注意,此選項需要 MongoDB 伺服器 >= 4.4。對於 MongoDB 4.2 和更早版本,設定此選項無效。
呼叫 query.allowDiskUse(v)
等效於 query.setOptions({ allowDiskUse: v })
範例
await query.find().sort({ name: 1 }).allowDiskUse(true);
// Equivalent:
await query.find().sort({ name: 1 }).allowDiskUse();
Query.prototype.and()
參數
array
«陣列» 條件陣列
傳回
- «查詢» this
參見
Query.prototype.batchSize()
參數
val
«數字»
參見
Query.prototype.box()
參數
val1
«物件|數字陣列» 左下角座標或左下角 (ll) 和右上角 (ur) 座標的物件[val2]
«數字陣列» 右上角座標
傳回
- «查詢» this
參見
指定 $box
條件
範例
const lowerLeft = [40.73083, -73.99756]
const upperRight= [40.741404, -73.988135]
query.where('loc').within().box(lowerLeft, upperRight)
query.box({ ll : lowerLeft, ur : upperRight })
Query.prototype.cast()
參數
[model]
«模型» 要轉換的模型。如果未設定,則預設為this.model
[obj]
«物件»
傳回
- «物件»
Query.prototype.catch()
參數
[reject]
«函式»
傳回
- «Promise»
執行查詢,傳回 Promise
,該 Promise 將使用 doc(s) 解析或使用錯誤拒絕。類似於 .then()
,但僅採用拒絕處理常式。
Query.prototype.center()
~已棄用~Query.prototype.centerSphere()
~已棄用~參數
[path]
«字串»val
«物件»
傳回
- «查詢» this
參見
已棄用 指定 $centerSphere
條件
已棄用。 請改用 circle。
範例
const area = { center: [50, 50], radius: 10 };
query.where('loc').within().centerSphere(area);
Query.prototype.circle()
參數
[path]
«字串»area
«物件»
傳回
- «查詢» this
參見
指定 $center
或 $centerSphere
條件。
範例
const area = { center: [50, 50], radius: 10, unique: true }
query.where('loc').within().circle(area)
// alternatively
query.circle('loc', area);
// spherical calculations
const area = { center: [50, 50], radius: 10, unique: true, spherical: true }
query.where('loc').within().circle(area)
// alternatively
query.circle('loc', area);
Query.prototype.clone()
傳回
- «查詢» 複本
建立此查詢的複本,以便您可以重新執行它。
範例
const q = Book.findOne({ title: 'Casino Royale' });
await q.exec();
await q.exec(); // Throws an error because you can't execute a query twice
await q.clone().exec(); // Works
Query.prototype.collation()
參數
value
«物件»
傳回
- «查詢» this
參見
將排序規則新增至此操作 (MongoDB 3.4 及更新版本)
Query.prototype.comment()
參數
val
«字串»
參見
Query.prototype.countDocuments()
參數
[filter]
«物件» mongodb 選擇器[options]
«物件»
傳回
- «查詢» this
參見
將此查詢指定為 countDocuments()
查詢。行為類似於 count()
,但當傳遞空篩選器 {}
時,它始終執行完整的集合掃描。
在 countDocuments()
如何處理 $where
和幾個地理空間運算符 與 count()
之間也存在一些細微差異。
此函數會觸發以下中間件。
countDocuments()
範例
const countQuery = model.where({ 'color': 'black' }).countDocuments();
query.countDocuments({ color: 'black' }).count().exec();
await query.countDocuments({ color: 'black' });
query.where('color', 'black').countDocuments().exec();
countDocuments()
函數類似於 count()
,但 countDocuments()
不支援一些運算符。以下是 count()
支援但 countDocuments()
不支援的運算符,以及建議的替代方案
$where
:$expr
$near
:$geoWithin
與$center
$nearSphere
:$geoWithin
與$centerSphere
Query.prototype.cursor()
參數
[options]
«物件»
傳回
- «QueryCursor»
參見
傳回 mongodb 驅動程式游標 的包裝函式。QueryCursor 會公開 Streams3 介面,以及 .next()
函數。
.cursor()
函數會觸發 pre find 鉤子,但不會觸發 post find 鉤子。
範例
// There are 2 ways to use a cursor. First, as a stream:
Thing.
find({ name: /^hello/ }).
cursor().
on('data', function(doc) { console.log(doc); }).
on('end', function() { console.log('Done!'); });
// Or you can use `.next()` to manually get the next doc in the stream.
// `.next()` returns a promise, so you can use promises or callbacks.
const cursor = Thing.find({ name: /^hello/ }).cursor();
cursor.next(function(error, doc) {
console.log(doc);
});
// Because `.next()` returns a promise, you can use co
// to easily iterate through all documents without loading them
// all into memory.
const cursor = Thing.find({ name: /^hello/ }).cursor();
for (let doc = await cursor.next(); doc != null; doc = await cursor.next()) {
console.log(doc);
}
有效的選項
transform
:可選函數,接受 mongoose 文件。該函數的傳回值將在data
上發出,並由.next()
傳回。
Query.prototype.deleteMany()
參數
[filter]
«物件|查詢» mongodb 選擇器[options]
«物件» 可選,請參閱Query.prototype.setOptions()
傳回
- «查詢» this
參見
將此查詢宣告和/或執行為 deleteMany()
操作。運作方式類似於 remove,但它會刪除集合中符合 filter
的每個文件,而不管 single
的值為何。
此函數會觸發 deleteMany
中間件。
範例
await Character.deleteMany({ name: /Stark/, age: { $gte: 18 } });
此函數會呼叫 MongoDB 驅動程式的 Collection#deleteMany()
函數。傳回的 promise 會解析為包含 3 個屬性的物件
ok
:如果沒有發生錯誤,則為1
deletedCount
:已刪除的文件數n
:已刪除的文件數。等於deletedCount
。
範例
const res = await Character.deleteMany({ name: /Stark/, age: { $gte: 18 } });
// `0` if no docs matched the filter, number of docs deleted otherwise
res.deletedCount;
Query.prototype.deleteOne()
參數
[filter]
«物件|查詢» mongodb 選擇器[options]
«物件» 可選,請參閱Query.prototype.setOptions()
傳回
- «查詢» this
參見
將此查詢宣告和/或執行為 deleteOne()
操作。運作方式類似於 remove,但它最多會刪除一個文件,而不管 single
選項為何。
此函數會觸發 deleteOne
中間件。
範例
await Character.deleteOne({ name: 'Eddard Stark' });
此函數會呼叫 MongoDB 驅動程式的 Collection#deleteOne()
函數。傳回的 promise 會解析為包含 3 個屬性的物件
ok
:如果沒有發生錯誤,則為1
deletedCount
:已刪除的文件數n
:已刪除的文件數。等於deletedCount
。
範例
const res = await Character.deleteOne({ name: 'Eddard Stark' });
// `1` if MongoDB deleted a doc, `0` if no docs matched the filter `{ name: ... }`
res.deletedCount;
Query.prototype.distinct()
參數
[field]
«字串»[filter]
«物件|查詢»[options]
«物件»
傳回
- «查詢» this
參見
宣告或執行 distinct() 操作。
此函數不會觸發任何中間件。
範例
distinct(field, conditions, options)
distinct(field, conditions)
distinct(field)
distinct()
Query.prototype.elemMatch()
參數
path
«字串|物件|函式»filter
«物件|函式»
傳回
- «查詢» this
參見
指定 $elemMatch
條件
範例
query.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}})
query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}})
query.elemMatch('comment', function (elem) {
elem.where('author').equals('autobot');
elem.where('votes').gte(5);
})
query.where('comment').elemMatch(function (elem) {
elem.where({ author: 'autobot' });
elem.where('votes').gte(5);
})
Query.prototype.equals()
參數
val
«物件»
傳回
- «查詢» this
Query.prototype.error()
參數
err
«錯誤|null» 如果設定,exec()
將在將查詢傳送至 MongoDB 之前快速失敗
傳回
- «查詢» this
取得/設定此查詢的錯誤旗標。如果此旗標不是 null 或未定義,則 exec()
promise 將在不執行的情況下拒絕。
範例
Query().error(); // Get current error value
Query().error(null); // Unset the current error
Query().error(new Error('test')); // `exec()` will resolve with test
Schema.pre('find', function() {
if (!this.getQuery().userId) {
this.error(new Error('Not allowed to query without setting userId'));
}
});
請注意,查詢轉換會在鉤子之後執行,因此轉換錯誤將覆寫自訂錯誤。
範例
const TestSchema = new Schema({ num: Number });
const TestModel = db.model('Test', TestSchema);
TestModel.find({ num: 'not a number' }).error(new Error('woops')).exec(function(error) {
// `error` will be a cast error because `num` failed to cast
});
Query.prototype.estimatedDocumentCount()
參數
[options]
«物件» 透明地傳遞到 MongoDB 驅動程式
傳回
- «查詢» this
參見
將此查詢指定為 estimatedDocumentCount()
查詢。對於大型集合而言,比使用 countDocuments()
更快,因為 estimatedDocumentCount()
使用集合元數據而不是掃描整個集合。
estimatedDocumentCount()
不接受篩選器。Model.find({ foo: bar }).estimatedDocumentCount()
等效於 Model.find().estimatedDocumentCount()
此函數會觸發以下中間件。
estimatedDocumentCount()
範例
await Model.find().estimatedDocumentCount();
Query.prototype.exec()
參數
[operation]
«字串|函式»
傳回
- «Promise»
Query.prototype.exists()
參數
[path]
«字串»val
«Boolean»
傳回
- «查詢» this
參見
指定一個 $exists
條件。
範例
// { name: { $exists: true }}
Thing.where('name').exists()
Thing.where('name').exists(true)
Thing.find().exists('name')
// { name: { $exists: false }}
Thing.where('name').exists(false);
Thing.find().exists('name', false);
Query.prototype.explain()
參數
[verbose]
«String» 詳細模式。可以是 'queryPlanner'、'executionStats' 或 'allPlansExecution'。預設值為 'queryPlanner'。
傳回
- «查詢» this
設定 explain
選項,這會使此查詢返回詳細的執行統計資訊,而不是實際的查詢結果。此方法對於確定您的查詢使用哪個索引很有用。
呼叫 query.explain(v)
等同於 query.setOptions({ explain: v })
。
範例
const query = new Query();
const res = await query.find({ a: 1 }).explain('queryPlanner');
console.log(res);
Query.prototype.finally()
參數
[onFinally]
«Function»
傳回
- «Promise»
執行查詢,返回一個 Promise
,該 Promise 將以鏈接的 .finally()
解析。
Query.prototype.find()
參數
[filter]
«Object|ObjectId» mongodb 過濾器。如果未指定,則返回所有文件。
傳回
- «查詢» this
尋找所有符合 selector
的文件。結果將是文件的陣列。
如果結果中有太多文件無法放入記憶體,請使用 Query.prototype.cursor()
。
範例
const arr = await Movie.find({ year: { $gte: 1980, $lte: 1989 } });
Query.prototype.findOne()
參數
[filter]
«物件» mongodb 選擇器[projection]
«Object» 可選的返回欄位。[options]
«Object» 請參閱setOptions()
。[options.translateAliases=null]
«Boolean» 如果設定為true
,則會轉換filter
、projection
、update
和distinct
中任何已定義的別名。如果同一個物件上同時定義了別名和原始屬性,則會拋出錯誤。
傳回
- «查詢» this
參見
宣告此查詢為 findOne 操作。執行時,找到的第一個文件將傳遞給回呼函數。
查詢的結果是單個文件,如果沒有找到任何文件,則為 null
。
- 注意:
conditions
是可選的,如果conditions
為 null 或 undefined,mongoose 將向 MongoDB 發送一個空的findOne
命令,這將返回一個任意的文件。如果您要按_id
查詢,請改用Model.findById()
。
此函數會觸發以下中間件。
findOne()
範例
const query = Kitten.where({ color: 'white' });
const kitten = await query.findOne();
Query.prototype.findOneAndDelete()
參數
[filter]
«Object»[options]
«物件»[options.includeResultMetadata]
«Boolean» 如果為 true,則返回完整的 來自 MongoDB 驅動程式的 ModifyResult,而不僅僅是文件。[options.session=null]
«ClientSession» 與此查詢關聯的會話。請參閱 交易文件。[options.strict]
«Boolean|String» 覆蓋 schema 的 strict 模式選項。
傳回
- «查詢» this
參見
發出 MongoDB findOneAndDelete 命令。
尋找符合條件的文件,將其刪除,並返回找到的文件(如果有)。
此函數會觸發以下中間件。
findOneAndDelete()
可用的選項
sort
:如果條件找到多個文件,則設定排序順序以選擇要更新的文件。maxTimeMS
:設定查詢的時間限制 - 需要 mongodb >= 2.6.0。
回呼簽名
function(error, doc) {
// error: any errors that occurred
// doc: the document before updates are applied if `new: false`, or after updates if `new = true`
}
範例
A.where().findOneAndDelete(conditions, options) // return Query
A.where().findOneAndDelete(conditions) // returns Query
A.where().findOneAndDelete() // returns Query
Query.prototype.findOneAndReplace()
參數
[filter]
«Object»[replacement]
«Object»[options]
«物件»[options.includeResultMetadata]
«Boolean» 如果為 true,則返回完整的 來自 MongoDB 驅動程式的 ModifyResult,而不僅僅是文件。[options.session=null]
«ClientSession» 與此查詢關聯的會話。請參閱 交易文件。[options.strict]
«Boolean|String» 覆蓋 schema 的 strict 模式選項。[options.new=false]
«Boolean» 預設情況下,findOneAndUpdate()
返回 在 應用update
之前 的文件。如果您設定new: true
,findOneAndUpdate()
將會給您應用update
之後的物件。[options.lean]
«Object» 如果為真值,mongoose 將返回文件作為純 JavaScript 物件,而不是 mongoose 文件。請參閱Query.lean()
和 Mongoose lean 教學。[options.session=null]
«ClientSession» 與此查詢關聯的會話。請參閱 交易文件。[options.strict]
«Boolean|String» 覆蓋 schema 的 strict 模式選項。[options.timestamps=null]
«Boolean» 如果設定為false
並且啟用schema 層級的時間戳記,則跳過此更新的時間戳記。請注意,這允許您覆寫時間戳記。如果未設定 schema 層級的時間戳記,則不會執行任何操作。[options.returnOriginal=null]
«Boolean»new
選項的別名。returnOriginal: false
等同於new: true
。[options.translateAliases=null]
«Boolean» 如果設定為true
,則會轉換filter
、projection
、update
和distinct
中任何已定義的別名。如果同一個物件上同時定義了別名和原始屬性,則會拋出錯誤。
傳回
- «查詢» this
發出 MongoDB findOneAndReplace 命令。
尋找符合條件的文件,將其刪除,並返回找到的文件(如果有)。
此函數會觸發以下中間件。
findOneAndReplace()
可用的選項
sort
:如果條件找到多個文件,則設定排序順序以選擇要更新的文件。maxTimeMS
:設定查詢的時間限制 - 需要 mongodb >= 2.6.0。includeResultMetadata
:如果為 true,則返回完整的 來自 MongoDB 驅動程式的 ModifyResult,而不僅僅是文件。
回呼簽名
function(error, doc) {
// error: any errors that occurred
// doc: the document before updates are applied if `new: false`, or after updates if `new = true`
}
範例
A.where().findOneAndReplace(filter, replacement, options); // return Query
A.where().findOneAndReplace(filter); // returns Query
A.where().findOneAndReplace(); // returns Query
Query.prototype.findOneAndUpdate()
參數
[filter]
«物件|查詢»[doc]
«Object»[options]
«物件»[options.includeResultMetadata]
«Boolean» 如果為 true,則返回完整的 來自 MongoDB 驅動程式的 ModifyResult,而不僅僅是文件。[options.strict]
«Boolean|String» 覆蓋 schema 的 strict 模式選項。[options.session=null]
«ClientSession» 與此查詢關聯的會話。請參閱 交易文件。[options.multipleCastError]
«Boolean» 預設情況下,mongoose 只返回在轉換查詢時發生的第一個錯誤。開啟此選項可彙總所有轉換錯誤。[options.new=false]
«Boolean» 預設情況下,findOneAndUpdate()
返回 在 應用update
之前 的文件。如果您設定new: true
,findOneAndUpdate()
將會給您應用update
之後的物件。[options.lean]
«Object» 如果為真值,mongoose 將返回文件作為純 JavaScript 物件,而不是 mongoose 文件。請參閱Query.lean()
和 Mongoose lean 教學。[options.session=null]
«ClientSession» 與此查詢關聯的會話。請參閱 交易文件。[options.strict]
«Boolean|String» 覆蓋 schema 的 strict 模式選項。[options.timestamps=null]
«Boolean» 如果設定為false
並且啟用schema 層級的時間戳記,則跳過此更新的時間戳記。請注意,這允許您覆寫時間戳記。如果未設定 schema 層級的時間戳記,則不會執行任何操作。[options.returnOriginal=null]
«Boolean»new
選項的別名。returnOriginal: false
等同於new: true
。[options.translateAliases=null]
«Boolean» 如果設定為true
,則會轉換filter
、projection
、update
和distinct
中任何已定義的別名。如果同一個物件上同時定義了別名和原始屬性,則會拋出錯誤。[options.overwriteDiscriminatorKey=false]
«Boolean» 預設情況下,Mongoose 會從update
中移除識別符鍵更新,將overwriteDiscriminatorKey
設定為true
以允許更新識別符鍵。
傳回
- «查詢» this
參見
發出 mongodb findOneAndUpdate()
命令。
尋找符合條件的文件,根據 update
參數更新它,傳遞任何 options
,並返回找到的文件(如果有)。
此函數會觸發以下中間件。
findOneAndUpdate()
可用的選項
new
:bool - 如果為 true,則返回修改後的文件,而不是原始文件。預設值為 false (在 4.0 中變更)。upsert
:bool - 如果物件不存在則建立該物件。預設值為 false。fields
:{Object|String} - 欄位選擇。等同於.select(fields).findOneAndUpdate()
。sort
:如果條件找到多個文件,則設定排序順序以選擇要更新的文件。maxTimeMS
:設定查詢的時間限制 - 需要 mongodb >= 2.6.0。runValidators
:如果為 true,則在此命令上執行更新驗證器。更新驗證器根據模型的 schema 驗證更新操作。setDefaultsOnInsert
:預設值為true
。如果setDefaultsOnInsert
和upsert
為 true,如果建立新文件,mongoose 將應用模型 schema 中指定的預設值。
範例
query.findOneAndUpdate(conditions, update, options) // returns Query
query.findOneAndUpdate(conditions, update) // returns Query
query.findOneAndUpdate(update) // returns Query
query.findOneAndUpdate() // returns Query
Query.prototype.geometry()
參數
object
«Object» 必須包含一個type
屬性,它是一個字串,和一個coordinates
屬性,它是一個陣列。請參閱範例。
傳回
- «查詢» this
參見
指定 $geometry
條件。
範例
const polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]]
query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA })
// or
const polyB = [[ 0, 0 ], [ 1, 1 ]]
query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB })
// or
const polyC = [ 0, 0 ]
query.where('loc').within().geometry({ type: 'Point', coordinates: polyC })
// or
query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC })
該參數會分配給最近傳遞給 where()
的路徑。
注意
geometry()
必須 在 intersects()
或 within()
之後使用。
object
參數必須包含 type
和 coordinates
屬性。
- type {String}
- coordinates {Array}
Query.prototype.get()
參數
path
«String|Object» 要取得的路徑或鍵/值對的物件。
傳回
- «查詢» this
對於更新操作,返回更新的 $set
中路徑的值。對於編寫可以用於更新操作和 save()
的 getter/setter 很有用。
範例
const query = Model.updateOne({}, { $set: { name: 'Jean-Luc Picard' } });
query.get('name'); // 'Jean-Luc Picard'
Query.prototype.getFilter()
傳回
- «Object» 目前的查詢篩選器。
以 POJO 形式返回目前的查詢篩選器 (也稱為條件)。
範例
const query = new Query();
query.find({ a: 1 }).where('b').gt(2);
query.getFilter(); // { a: 1, b: { $gt: 2 } }
Query.prototype.getOptions()
傳回
- «Object» 選項。
取得查詢選項。
範例
const query = new Query();
query.limit(10);
query.setOptions({ maxTimeMS: 1000 });
query.getOptions(); // { limit: 10, maxTimeMS: 1000 }
Query.prototype.getPopulatedPaths()
傳回
- «Array» 代表已填充路徑的字串陣列。
取得此查詢要填充的路徑清單。
範例
bookSchema.pre('findOne', function() {
let keys = this.getPopulatedPaths(); // ['author']
});
...
Book.findOne({}).populate('author');
範例
// Deep populate
const q = L1.find().populate({
path: 'level2',
populate: { path: 'level3' }
});
q.getPopulatedPaths(); // ['level2', 'level2.level3']
Query.prototype.getQuery()
傳回
- «Object» 目前的查詢篩選器。
返回目前的查詢篩選器。等同於 getFilter()
。
您應該盡可能使用 getFilter()
而不是 getQuery()
。getQuery()
可能會在未來的版本中被棄用。
範例
const query = new Query();
query.find({ a: 1 }).where('b').gt(2);
query.getQuery(); // { a: 1, b: { $gt: 2 } }
Query.prototype.getUpdate()
傳回
- «Object» 目前的更新操作。
以 JSON 物件形式返回目前的更新操作。
範例
const query = new Query();
query.updateOne({}, { $set: { a: 5 } });
query.getUpdate(); // { $set: { a: 5 } }
Query.prototype.gt()
參數
[path]
«字串»val
«數字»
參見
指定一個 $gt
查詢條件。
當使用一個參數呼叫時,將使用傳遞給 where()
的最近路徑。
範例
Thing.find().where('age').gt(21);
// or
Thing.find().gt('age', 21);
Query.prototype.gte()
參數
[path]
«字串»val
«數字»
參見
指定一個 $gte
查詢條件。
當使用一個參數呼叫時,將使用傳遞給 where()
的最近路徑。
Query.prototype.hint()
參數
val
«Object» 提示物件。
傳回
- «查詢» this
參見
Query.prototype.in()
參數
[path]
«字串»val
«陣列»
參見
指定一個 $in
查詢條件。
當使用一個參數呼叫時,將使用傳遞給 where()
的最近路徑。
Query.prototype.intersects()
參數
[arg]
«Object»
傳回
- «查詢» this
參見
宣告 geometry()
的相交查詢。
範例
query.where('path').intersects().geometry({
type: 'LineString',
coordinates: [[180.0, 11.0], [180, 9.0]]
});
query.where('path').intersects({
type: 'LineString',
coordinates: [[180.0, 11.0], [180, 9.0]]
});
注意
必須 在 where()
之後使用。
注意
在 Mongoose 3.7 中,intersects
從 getter 更改為函數。如果您需要舊的語法,請使用這個。
Query.prototype.isPathSelectedInclusive()
參數
path
«String»
傳回
- «Boolean»
呼叫查詢中 isPathSelectedInclusive 的包裝函式。
Query.prototype.j()
參數
val
«boolean»
傳回
- «查詢» this
參見
請求確認此操作已持久儲存到 MongoDB 的磁碟上日誌。此選項僅對寫入資料庫的操作有效。
deleteOne()
deleteMany()
findOneAndDelete()
findOneAndReplace()
findOneAndUpdate()
updateOne()
updateMany()
預設為 schema 的 writeConcern.j
選項。
範例
await mongoose.model('Person').deleteOne({ name: 'Ned Stark' }).j(true);
Query.prototype.lean()
參數
bool
«Boolean|Object» 預設為 true。
傳回
- «查詢» this
設定 lean 選項。
從啟用 lean
選項的查詢返回的文件是純 javascript 物件,而不是Mongoose 文件。它們沒有 save
方法、getter/setter、虛擬屬性或其他 Mongoose 功能。
範例
new Query().lean() // true
new Query().lean(true)
new Query().lean(false)
const docs = await Model.find().lean();
docs[0] instanceof mongoose.Document; // false
Lean 非常適合高效能的唯讀情況,尤其是在與游標結合使用時。
如果您需要 lean()
的虛擬屬性、getter/setter 或預設值,則需要使用外掛程式。請參閱
Query.prototype.limit()
參數
val
«數字»
Query.prototype.lt()
參數
[path]
«字串»val
«數字»
參見
指定一個 $lt
查詢條件。
當使用一個參數呼叫時,將使用傳遞給 where()
的最近路徑。
Query.prototype.lte()
參數
[path]
«字串»val
«數字»
參見
指定一個 $lte
查詢條件。
當使用一個參數呼叫時,將使用傳遞給 where()
的最近路徑。
Query.prototype.maxDistance()
參數
[path]
«字串»val
«數字»
參見
指定一個 maxDistance
查詢條件。
當使用一個參數呼叫時,將使用傳遞給 where()
的最近路徑。
Query.prototype.maxTimeMS()
參數
[ms]
«Number» 毫秒數。
傳回
- «查詢» this
設定 maxTimeMS 選項。這將告知 MongoDB 伺服器,如果查詢或寫入操作執行時間超過 ms
毫秒,則中止。
呼叫 query.maxTimeMS(v)
等同於 query.setOptions({ maxTimeMS: v })
。
範例
const query = new Query();
// Throws an error 'operation exceeded time limit' as long as there's
// >= 1 doc in the queried collection
const res = await query.find({ $where: 'sleep(1000) || true' }).maxTimeMS(100);
Query.prototype.merge()
參數
source
«Query|Object»
傳回
- «查詢» this
將另一個查詢或條件物件合併到此查詢中。
當傳遞查詢時,會合併條件、欄位選擇和選項。
Query.prototype.mod()
參數
[path]
«字串»val
«Array» 長度必須為 2,第一個元素是divisor
,第二個元素是remainder
。
傳回
- «查詢» this
參見
指定一個 $mod
條件,篩選 path
屬性是一個數字且等於 divisor
除以 remainder
的文件。
範例
// All find products whose inventory is odd
Product.find().mod('inventory', [2, 1]);
Product.find().where('inventory').mod([2, 1]);
// This syntax is a little strange, but supported.
Product.find().where('inventory').mod(2, 1);
Query.prototype.model
類型
- «property»
Query.prototype.mongooseOptions()
參數
options
«Object» 如果指定,則會覆蓋目前的選項。
傳回
- «Object» 選項。
此查詢的目前 mongoose 特定選項的 getter/setter。以下是目前的 Mongoose 特定選項。
populate
:代表將要填充的路徑的陣列。每次呼叫Query.prototype.populate()
應有一個項目。lean
:如果為真值,Mongoose 將不會 水合化 從此查詢返回的任何文件。請參閱Query.prototype.lean()
以取得更多資訊。strict
:控制 Mongoose 如何處理更新中不在 schema 中的鍵。此選項預設為true
,這表示 Mongoose 將會靜默地移除更新中不在 schema 中的任何路徑。請參閱strict
模式文件以取得更多資訊。strictQuery
:控制 Mongoose 如何處理查詢filter
中不屬於 schema 的鍵。此選項預設為false
,這表示即使foo
不在 schema 中,Mongoose 也會允許Model.find({ foo: 'bar' })
。請參閱strictQuery
文件以獲取更多資訊。nearSphere
:使用$nearSphere
而非near()
。請參閱Query.prototype.nearSphere()
文件
Mongoose 為內部選項維護一個獨立的物件,因為 Mongoose 會將 Query.prototype.options
發送到 MongoDB 伺服器,而上述選項與 MongoDB 伺服器無關。
Query.prototype.ne()
參數
[path]
«字串»val
«any»
參見
指定 $ne
查詢條件。
當使用一個參數呼叫時,將使用傳遞給 where()
的最近路徑。
Query.prototype.near()
參數
[path]
«字串»val
«物件»
傳回
- «查詢» this
參見
指定 $near
或 $nearSphere
條件
這些運算子會傳回依距離排序的文件。
範例
query.where('loc').near({ center: [10, 10] });
query.where('loc').near({ center: [10, 10], maxDistance: 5 });
query.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true });
query.near('loc', { center: [10, 10], maxDistance: 5 });
Query.prototype.nearSphere()
~已棄用~參見
已棄用 指定 $nearSphere
條件
範例
query.where('loc').nearSphere({ center: [10, 10], maxDistance: 5 });
已棄用。 請改用 query.near()
並將 spherical
選項設定為 true
。
範例
query.where('loc').near({ center: [10, 10], spherical: true });
Query.prototype.nin()
參數
[path]
«字串»val
«陣列»
參見
指定 $nin
查詢條件。
當使用一個參數呼叫時,將使用傳遞給 where()
的最近路徑。
Query.prototype.nor()
參數
array
«陣列» 條件陣列
傳回
- «查詢» this
參見
Query.prototype.or()
參數
array
«陣列» 條件陣列
傳回
- «查詢» this
參見
Query.prototype.orFail()
參數
[err]
«Function|Error» 可選的錯誤,如果沒有文件符合filter
則拋出。如果未指定,orFail()
將會拋出DocumentNotFoundError
傳回
- «查詢» this
如果沒有文件符合給定的 filter
,則使此查詢拋出錯誤。這對於與 async/await 整合非常方便,因為 orFail()
可以節省您額外的 if
語句來檢查是否沒有找到文件。
範例
// Throws if no doc returned
await Model.findOne({ foo: 'bar' }).orFail();
// Throws if no document was updated. Note that `orFail()` will still
// throw if the only document that matches is `{ foo: 'bar', name: 'test' }`,
// because `orFail()` will throw if no document was _updated_, not
// if no document was _found_.
await Model.updateOne({ foo: 'bar' }, { name: 'test' }).orFail();
// Throws "No docs found!" error if no docs match `{ foo: 'bar' }`
await Model.find({ foo: 'bar' }).orFail(new Error('No docs found!'));
// Throws "Not found" error if no document was found
await Model.findOneAndUpdate({ foo: 'bar' }, { name: 'test' }).
orFail(() => Error('Not found'));
Query.prototype.polygon()
參數
[path]
«String|Array»[...coordinatePairs]
«Array|Object»
傳回
- «查詢» this
參見
指定 $polygon
條件
範例
query.where('loc').within().polygon([10, 20], [13, 25], [7, 15]);
query.polygon('loc', [10, 20], [13, 25], [7, 15]);
Query.prototype.populate()
參數
path
«Object|String|Array[String]» 要填充的路徑或指定所有參數的物件[select]
«Object|String» 填充查詢的欄位選擇[model]
«Model» 您希望用於填充的模型。如果未指定,填充將會依據 Schema 的ref
欄位中的名稱查找模型。[match]
«Object» 填充查詢的條件[options]
«Object» 填充查詢的選項 (排序等)[options.path=null]
«String» 要填充的路徑。[options.retainNullValues=false]
«boolean» 預設情況下,Mongoose 會從填充的陣列中移除 null 和 undefined 值。使用此選項可讓populate()
保留null
和undefined
陣列條目。[options.getters=false]
«boolean» 如果為 true,Mongoose 將會呼叫在localField
上定義的任何 getter。預設情況下,Mongoose 會取得localField
的原始值。例如,如果您想將lowercase
getter 新增到您的localField
,則需要將此選項設定為true
。[options.clone=false]
«boolean» 當您執行BlogPost.find().populate('author')
時,具有相同作者的網誌文章將會共用 1 個author
文件的副本。啟用此選項可讓 Mongoose 在指派之前複製填充的文件。[options.match=null]
«Object|Function» 將額外的篩選器新增到填充查詢。可以是包含MongoDB 查詢語法的篩選器物件,或傳回篩選器物件的函式。[options.transform=null]
«Function» Mongoose 將會對每個填充的文件呼叫的函式,可讓您轉換填充的文件。[options.options=null]
«Object» 額外的選項,如limit
和lean
。
傳回
- «查詢» this
參見
指定應該使用其他文件填充的路徑。
範例
let book = await Book.findOne().populate('authors');
book.title; // 'Node.js in Action'
book.authors[0].name; // 'TJ Holowaychuk'
book.authors[1].name; // 'Nathan Rajlich'
let books = await Book.find().populate({
path: 'authors',
// `match` and `sort` apply to the Author model,
// not the Book model. These options do not affect
// which documents are in `books`, just the order and
// contents of each book document's `authors`.
match: { name: new RegExp('.*h.*', 'i') },
sort: { name: -1 }
});
books[0].title; // 'Node.js in Action'
// Each book's `authors` are sorted by name, descending.
books[0].authors[0].name; // 'TJ Holowaychuk'
books[0].authors[1].name; // 'Marc Harter'
books[1].title; // 'Professional AngularJS'
// Empty array, no authors' name has the letter 'h'
books[1].authors; // []
路徑會在查詢執行並收到回應後填充。然後會針對指定的每個填充路徑執行個別的查詢。在也傳回每個查詢的回應後,結果會傳遞給回呼。
Query.prototype.post()
參數
fn
«Function»
傳回
- «Promise»
將後置中介軟體新增到此查詢實例。不會影響其他查詢。
範例
const q1 = Question.find({ answer: 42 });
q1.post(function middleware() {
console.log(this.getFilter());
});
await q1.exec(); // Prints "{ answer: 42 }"
// Doesn't print anything, because `middleware()` is only
// registered on `q1`.
await Question.find({ answer: 42 });
Query.prototype.pre()
參數
fn
«Function»
傳回
- «Promise»
將前置中介軟體新增到此查詢實例。不會影響其他查詢。
範例
const q1 = Question.find({ answer: 42 });
q1.pre(function middleware() {
console.log(this.getFilter());
});
await q1.exec(); // Prints "{ answer: 42 }"
// Doesn't print anything, because `middleware()` is only
// registered on `q1`.
await Question.find({ answer: 42 });
Query.prototype.projection()
參數
arg
«Object|null»
傳回
- «Object» 目前的投影
取得/設定目前的投影 (也稱為欄位)。傳遞 null
以移除目前的投影。
與 projection()
不同,select()
函式會就地修改目前的投影。此函式會覆寫現有的投影。
範例
const q = Model.find();
q.projection(); // null
q.select('a b');
q.projection(); // { a: 1, b: 1 }
q.projection({ c: 1 });
q.projection(); // { c: 1 }
q.projection(null);
q.projection(); // null
Query.prototype.read()
參數
mode
«String» 列出的偏好選項或別名之一[tags]
«Array» 此查詢的可選標籤
傳回
- «查詢» this
參見
決定從哪個 MongoDB 節點讀取。
偏好設定
primary - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags.
secondary Read from secondary if available, otherwise error.
primaryPreferred Read from primary if available, otherwise a secondary.
secondaryPreferred Read from a secondary if available, otherwise read from the primary.
nearest All operations read from among the nearest candidates, but unlike other modes, this option will include both the primary and all secondaries in the random selection.
別名
p primary
pp primaryPreferred
s secondary
sp secondaryPreferred
n nearest
範例
new Query().read('primary')
new Query().read('p') // same as primary
new Query().read('primaryPreferred')
new Query().read('pp') // same as primaryPreferred
new Query().read('secondary')
new Query().read('s') // same as secondary
new Query().read('secondaryPreferred')
new Query().read('sp') // same as secondaryPreferred
new Query().read('nearest')
new Query().read('n') // same as nearest
// read from secondaries with matching tags
new Query().read('s', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }])
若要深入瞭解如何使用讀取偏好設定,請參閱此處。
Query.prototype.readConcern()
參數
level
«String» 列出的讀取關注層級或其別名之一
傳回
- «查詢» this
參見
設定查詢的 readConcern 選項。
範例
new Query().readConcern('local')
new Query().readConcern('l') // same as local
new Query().readConcern('available')
new Query().readConcern('a') // same as available
new Query().readConcern('majority')
new Query().readConcern('m') // same as majority
new Query().readConcern('linearizable')
new Query().readConcern('lz') // same as linearizable
new Query().readConcern('snapshot')
new Query().readConcern('s') // same as snapshot
讀取關注層級
local MongoDB 3.2+ The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back).
available MongoDB 3.6+ The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back).
majority MongoDB 3.2+ The query returns the data that has been acknowledged by a majority of the replica set members. The documents returned by the read operation are durable, even in the event of failure.
linearizable MongoDB 3.4+ The query returns data that reflects all successful majority-acknowledged writes that completed prior to the start of the read operation. The query may wait for concurrently executing writes to propagate to a majority of replica set members before returning results.
snapshot MongoDB 4.0+ Only available for operations within multi-document transactions. Upon transaction commit with write concern "majority", the transaction operations are guaranteed to have read from a snapshot of majority-committed data.
別名
l local
a available
m majority
lz linearizable
s snapshot
若要深入瞭解如何使用讀取關注,請參閱此處。
Query.prototype.regex()
參數
[path]
«字串»val
«String|RegExp»
參見
指定 $regex
查詢條件。
當使用一個參數呼叫時,將使用傳遞給 where()
的最近路徑。
Query.prototype.replaceOne()
參數
[filter]
«Object»[doc]
«Object» 更新指令[options]
«物件»[options.multipleCastError]
«Boolean» 預設情況下,mongoose 只返回在轉換查詢時發生的第一個錯誤。開啟此選項可彙總所有轉換錯誤。[options.strict]
«Boolean|String» 覆蓋 schema 的 strict 模式選項。[options.upsert=false]
«Boolean» 如果為 true 且找不到文件,則插入新的文件[options.writeConcern=null]
«Object» 設定複寫集的寫入關注。覆寫結構描述層級的寫入關注[options.timestamps=null]
«Boolean» 如果設定為false
且啟用結構描述層級的時間戳記,則跳過此更新的時間戳記。如果未設定結構描述層級的時間戳記,則無任何作用。[options.translateAliases=null]
«Boolean» 如果設定為true
,則會轉換filter
、projection
、update
和distinct
中任何已定義的別名。如果同一個物件上同時定義了別名和原始屬性,則會拋出錯誤。[callback]
«Function» 參數為 (error, writeOpResult)
傳回
- «查詢» this
參見
宣告和/或將此查詢作為 replaceOne() 操作執行。MongoDB 將會取代現有的文件,並且不會接受任何原子運算子 ($set
等)
注意 replaceOne 將不會觸發更新中介軟體。請改用 pre('replaceOne')
和 post('replaceOne')
。
範例
const res = await Person.replaceOne({ _id: 24601 }, { name: 'Jean Valjean' });
res.acknowledged; // Indicates if this write result was acknowledged. If not, then all other members of this result will be undefined.
res.matchedCount; // Number of documents that matched the filter
res.modifiedCount; // Number of documents that were modified
res.upsertedCount; // Number of documents that were upserted
res.upsertedId; // Identifier of the inserted document (if an upsert took place)
此函數會觸發以下中間件。
replaceOne()
Query.prototype.sanitizeProjection()
參數
value
«Boolean»
傳回
- «查詢» this
參見
設定此查詢的 sanitizeProjection
選項。如果設定,sanitizeProjection
會執行兩項操作
- 強制投影值為數字,而不是字串。
- 防止使用
+
語法來覆寫預設取消選取的屬性。
使用 sanitizeProjection()
,您可以將可能不受信任的使用者資料傳遞給 .select()
。
範例
const userSchema = new Schema({
name: String,
password: { type: String, select: false }
});
const UserModel = mongoose.model('User', userSchema);
const { _id } = await UserModel.create({ name: 'John', password: 'secret' })
// The MongoDB server has special handling for string values that start with '$'
// in projections, which can lead to unexpected leaking of sensitive data.
let doc = await UserModel.findOne().select({ name: '$password' });
doc.name; // 'secret'
doc.password; // undefined
// With `sanitizeProjection`, Mongoose forces all projection values to be numbers
doc = await UserModel.findOne().sanitizeProjection(true).select({ name: '$password' });
doc.name; // 'John'
doc.password; // undefined
// By default, Mongoose supports projecting in `password` using `+password`
doc = await UserModel.findOne().select('+password');
doc.password; // 'secret'
// With `sanitizeProjection`, Mongoose prevents projecting in `password` and other
// fields that have `select: false` in the schema.
doc = await UserModel.findOne().sanitizeProjection(true).select('+password');
doc.password; // undefined
Query.prototype.select()
參數
arg
«Object|String|Array[String]»
傳回
- «查詢» this
參見
指定要包含或排除的檔案欄位(也稱為查詢「投影」)
使用字串語法時,在路徑前面加上 -
將會將該路徑標示為排除。當路徑沒有 -
字首時,會包含該路徑。最後,如果路徑有 +
字首,則會強制包含該路徑,這對於在結構描述層級排除的路徑非常有用。
投影必須是包含或排除。換句話說,您必須列出要包含的欄位(這會排除所有其他欄位),或列出要排除的欄位(這表示包含所有其他欄位)。_id
欄位是唯一的例外,因為 MongoDB 預設會包含它。
範例
// include a and b, exclude other fields
query.select('a b');
// Equivalent syntaxes:
query.select(['a', 'b']);
query.select({ a: 1, b: 1 });
// exclude c and d, include other fields
query.select('-c -d');
// Use `+` to override schema-level `select: false` without making the
// projection inclusive.
const schema = new Schema({
foo: { type: String, select: false },
bar: String
});
// ...
query.select('+foo'); // Override foo's `select: false` without excluding `bar`
// or you may use object notation, useful when
// you have keys already prefixed with a "-"
query.select({ a: 1, b: 1 });
query.select({ c: 0, d: 0 });
Additional calls to select can override the previous selection:
query.select({ a: 1, b: 1 }).select({ b: 0 }); // selection is now { a: 1 }
query.select({ a: 0, b: 0 }).select({ b: 1 }); // selection is now { a: 0 }
Query.prototype.selected()
傳回
- «Boolean»
判斷是否已進行欄位選取。
Query.prototype.selectedExclusively()
傳回
- «Boolean»
判斷是否已進行排除欄位選取。
query.selectedExclusively(); // false
query.select('-name');
query.selectedExclusively(); // true
query.selectedInclusively(); // false
Query.prototype.selectedInclusively()
傳回
- «Boolean»
判斷是否已進行包含欄位選取。
query.selectedInclusively(); // false
query.select('name');
query.selectedInclusively(); // true
Query.prototype.session()
參數
[session]
«ClientSession» 來自await conn.startSession()
傳回
- «查詢» this
參見
設定與此查詢相關聯的MongoDB 工作階段。工作階段是您如何將查詢標記為交易的一部分。
呼叫 session(null)
會從此查詢中移除工作階段。
範例
const s = await mongoose.startSession();
await mongoose.model('Person').findOne({ name: 'Axl Rose' }).session(s);
Query.prototype.set()
參數
path
«String|Object» 要設定的路徑或鍵/值配對的物件[val]
«Any» 要設定的值
傳回
- «查詢» this
將 $set
新增到此查詢的更新,而不變更操作。這對於查詢中介軟體非常有用,因此無論您使用 updateOne()
、updateMany()
、findOneAndUpdate()
等,都可以新增更新。
範例
// Updates `{ $set: { updatedAt: new Date() } }`
new Query().updateOne({}, {}).set('updatedAt', new Date());
new Query().updateMany({}, {}).set({ updatedAt: new Date() });
Query.prototype.setOptions()
參數
options
«Object»
傳回
- «查詢» this
設定查詢選項。某些選項僅對特定操作有意義。
選項
以下選項僅適用於 find()
以下選項僅適用於寫入操作:updateOne()
、updateMany()
、replaceOne()
、findOneAndUpdate()
和 findByIdAndUpdate()
- upsert
- writeConcern
- timestamps:如果在結構描述中設定了
timestamps
,則將此選項設定為false
以跳過該特定更新的時間戳記。如果結構描述選項中未啟用timestamps
,則無任何作用。 - overwriteDiscriminatorKey:允許在更新中設定區別鍵。如果更新變更了區別鍵,則將使用正確的區別結構描述。
以下選項僅適用於 find()
、findOne()
、findById()
、findOneAndUpdate()
、findOneAndReplace()
、findOneAndDelete()
和 findByIdAndUpdate()
- lean
- populate
- projection
- sanitizeProjection
- useBigInt64
以下選項僅適用於除 updateOne()
、updateMany()
、deleteOne()
和 deleteMany()
之外的所有操作
以下選項適用於 find()
、findOne()
、findOneAndUpdate()
、findOneAndDelete()
、updateOne()
和 deleteOne()
以下選項適用於 findOneAndUpdate()
和 findOneAndDelete()
- includeResultMetadata
以下選項適用於所有操作
Query.prototype.setQuery()
參數
new
«Object» 查詢條件
傳回
- «undefined,void»
將查詢條件設定為提供的 JSON 物件。
範例
const query = new Query();
query.find({ a: 1 })
query.setQuery({ a: 2 });
query.getQuery(); // { a: 2 }
Query.prototype.setUpdate()
參數
new
«Object» 更新操作
傳回
- «undefined,void»
將目前的更新操作設定為新值。
範例
const query = new Query();
query.updateOne({}, { $set: { a: 5 } });
query.setUpdate({ $set: { b: 6 } });
query.getUpdate(); // { $set: { b: 6 } }
Query.prototype.size()
參數
[path]
«字串»val
«數字»
參見
指定 $size
查詢條件。
當使用一個參數呼叫時,將使用傳遞給 where()
的最近路徑。
範例
const docs = await MyModel.where('tags').size(0).exec();
assert(Array.isArray(docs));
console.log('documents with 0 tags', docs);
Query.prototype.skip()
參數
val
«數字»
參見
Query.prototype.slice()
參數
[path]
«字串»val
«Number|Array» 要分割的元素數或包含要跳過的元素數和要分割的元素數的陣列
傳回
- «查詢» this
參見
為陣列指定 $slice
投影。
範例
query.slice('comments', 5); // Returns the first 5 comments
query.slice('comments', -5); // Returns the last 5 comments
query.slice('comments', [10, 5]); // Returns the first 5 comments after the 10-th
query.where('comments').slice(5); // Returns the first 5 comments
query.where('comments').slice([-10, 5]); // Returns the first 5 comments after the 10-th to last
注意:如果要分割的元素數的絕對值大於陣列中的元素數,則將會傳回所有陣列元素。
// Given `arr`: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
query.slice('arr', 20); // Returns [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
query.slice('arr', -20); // Returns [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
注意:如果要跳過的元素數為正數且大於陣列中的元素數,則將會傳回空陣列。
// Given `arr`: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
query.slice('arr', [20, 5]); // Returns []
注意:如果要跳過的元素數為負數且其絕對值大於陣列中的元素數,則起始位置為陣列的開頭。
// Given `arr`: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
query.slice('arr', [-20, 5]); // Returns [1, 2, 3, 4, 5]
Query.prototype.sort()
參數
arg
«Object|String|Array<Array<string|number>>»[options]
«物件»[options.override=false]
«Boolean» 如果為 true,則將現有的排序選項取代為arg
傳回
- «查詢» this
參見
設定排序順序
如果傳遞了物件,則允許的值為 asc
、desc
、ascending
、descending
、1
和 -1
。
如果傳遞了字串,則必須是空格分隔的路徑名稱清單。除非路徑名稱有 -
字首,否則每個路徑的排序順序為遞增,這將被視為遞減。
範例
// sort by "field" ascending and "test" descending
query.sort({ field: 'asc', test: -1 });
// equivalent
query.sort('field -test');
// also possible is to use a array with array key-value pairs
query.sort([['field', 'asc']]);
注意
不能與 distinct()
一起使用
Query.prototype.tailable()
參數
bool
«Boolean» 預設為 true[opts]
«Object» 要設定的選項。[opts.awaitData]
«Boolean» 預設為 false。設定為 true 可讓游標保持開啟,即使沒有資料。[opts.maxAwaitTimeMS]
«Number» 伺服器等待新文件滿足尾部游標查詢的最長時間(毫秒)。需要 `tailable` 和 `awaitData` 都為 true。
參見
設定尾部選項(用於 capped 集合)。
範例
query.tailable(); // true
query.tailable(true);
query.tailable(false);
// Set both `tailable` and `awaitData` options
query.tailable({ awaitData: true });
注意
不能與 distinct()
一起使用
Query.prototype.then()
參數
[resolve]
«Function»[reject]
«函式»
傳回
- «Promise»
執行查詢,返回一個 Promise
,該 Promise
將以 doc(s) 解析,或以錯誤拒絕。
更多關於 JavaScript 中的 then()
。
Query.prototype.toConstructor()
傳回
- «Query» Query 的子類別
將此查詢轉換為自定義的可重用查詢建構子,並保留所有引數和選項。
範例
// Create a query for adventure movies and read from the primary
// node in the replica-set unless it is down, in which case we'll
// read from a secondary node.
const query = Movie.find({ tags: 'adventure' }).read('primaryPreferred');
// create a custom Query constructor based off these settings
const Adventure = query.toConstructor();
// further narrow down our query results while still using the previous settings
await Adventure().where({ name: /^Life/ }).exec();
// since Adventure is a stand-alone constructor we can also add our own
// helper methods and getters without impacting global queries
Adventure.prototype.startsWith = function (prefix) {
this.where({ name: new RegExp('^' + prefix) })
return this;
}
Object.defineProperty(Adventure.prototype, 'highlyRated', {
get: function () {
this.where({ rating: { $gt: 4.5 }});
return this;
}
})
await Adventure().highlyRated.startsWith('Life').exec();
Query.prototype.transform()
參數
fn
«Function» 用於轉換查詢結果的函式。
傳回
- «查詢» this
執行函式 fn
,並將 fn
的回傳值視為查詢要解析的新值。
您傳遞給 transform()
的任何函式都將在任何 post hook 之後執行。
範例
const res = await MyModel.findOne().transform(res => {
// Sets a `loadedAt` property on the doc that tells you the time the
// document was loaded.
return res == null ?
res :
Object.assign(res, { loadedAt: new Date() });
});
Query.prototype.updateMany()
參數
[filter]
«Object»[update]
«Object|Array» 更新命令。如果為陣列,則此更新將被視為更新管道,而不是轉換。[options]
«物件»[options.multipleCastError]
«Boolean» 預設情況下,mongoose 只返回在轉換查詢時發生的第一個錯誤。開啟此選項可彙總所有轉換錯誤。[options.strict]
«Boolean|String» 覆蓋 schema 的 strict 模式選項。[options.upsert=false]
«Boolean» 如果為 true 且找不到文件,則插入新的文件[options.writeConcern=null]
«Object» 設定複寫集的寫入關注。覆寫結構描述層級的寫入關注[options.timestamps=null]
«Boolean» 如果設定為false
且啟用結構描述層級的時間戳記,則跳過此更新的時間戳記。如果未設定結構描述層級的時間戳記,則無任何作用。[options.translateAliases=null]
«Boolean» 如果設定為true
,則會轉換filter
、projection
、update
和distinct
中任何已定義的別名。如果同一個物件上同時定義了別名和原始屬性,則會拋出錯誤。[options.overwriteDiscriminatorKey=false]
«Boolean» 預設情況下,Mongoose 會從update
中移除識別符鍵更新,將overwriteDiscriminatorKey
設定為true
以允許更新識別符鍵。[callback]
«Function» 參數為 (error, writeOpResult)
傳回
- «查詢» this
參見
宣告和/或執行此查詢作為 updateMany() 操作。MongoDB 將更新符合 filter
的所有文件(而不僅僅是第一個)。
注意 updateMany 不會觸發更新中介軟體。請改用 `pre('updateMany')` 和 `post('updateMany')`。
範例
const res = await Person.updateMany({ name: /Stark$/ }, { isDeleted: true });
res.n; // Number of documents matched
res.nModified; // Number of documents modified
此函數會觸發以下中間件。
updateMany()
Query.prototype.updateOne()
參數
[filter]
«Object»[update]
«Object|Array» 更新命令。如果為陣列,則此更新將被視為更新管道,而不是轉換。[options]
«物件»[options.multipleCastError]
«Boolean» 預設情況下,mongoose 只返回在轉換查詢時發生的第一個錯誤。開啟此選項可彙總所有轉換錯誤。[options.strict]
«Boolean|String» 覆蓋 schema 的 strict 模式選項。[options.upsert=false]
«Boolean» 如果為 true 且找不到文件,則插入新的文件[options.writeConcern=null]
«Object» 設定複寫集的寫入關注。覆寫結構描述層級的寫入關注[options.timestamps=null]
«Boolean» 如果設定為false
並且啟用schema 層級的時間戳記,則跳過此更新的時間戳記。請注意,這允許您覆寫時間戳記。如果未設定 schema 層級的時間戳記,則不會執行任何操作。[options.translateAliases=null]
«Boolean» 如果設定為true
,則會轉換filter
、projection
、update
和distinct
中任何已定義的別名。如果同一個物件上同時定義了別名和原始屬性,則會拋出錯誤。[options.overwriteDiscriminatorKey=false]
«Boolean» 預設情況下,Mongoose 會從update
中移除識別符鍵更新,將overwriteDiscriminatorKey
設定為true
以允許更新識別符鍵。[callback]
«Function» 參數為 (error, writeOpResult)
傳回
- «查詢» this
參見
宣告和/或執行此查詢作為 updateOne() 操作。MongoDB 將更新符合 filter
的第一個文件。
- 如果您想要覆寫整個文件,而不是使用像
$set
這樣的 原子運算子,請使用replaceOne()
。
注意 updateOne 不會觸發更新中介軟體。請改用 `pre('updateOne')` 和 `post('updateOne')`。
範例
const res = await Person.updateOne({ name: 'Jean-Luc Picard' }, { ship: 'USS Enterprise' });
res.acknowledged; // Indicates if this write result was acknowledged. If not, then all other members of this result will be undefined.
res.matchedCount; // Number of documents that matched the filter
res.modifiedCount; // Number of documents that were modified
res.upsertedCount; // Number of documents that were upserted
res.upsertedId; // Identifier of the inserted document (if an upsert took place)
此函數會觸發以下中間件。
updateOne()
Query.prototype.w()
參數
val
«String|number» 0 代表 fire-and-forget,1 代表由一個伺服器確認,'majority' 代表副本集的 majority,或 任何更進階的選項。
傳回
- «查詢» this
參見
設定指定的 mongod
伺服器數量,或 mongod
伺服器的標籤集,這些伺服器必須先確認此寫入,此寫入才被視為成功。此選項僅適用於寫入資料庫的操作。
deleteOne()
deleteMany()
findOneAndDelete()
findOneAndReplace()
findOneAndUpdate()
updateOne()
updateMany()
預設為 schema 的 writeConcern.w
選項
範例
// The 'majority' option means the `deleteOne()` promise won't resolve
// until the `deleteOne()` has propagated to the majority of the replica set
await mongoose.model('Person').
deleteOne({ name: 'Ned Stark' }).
w('majority');
Query.prototype.where()
參數
[path]
«String|Object»[val]
«any»
傳回
- «查詢» this
指定一個用於鏈接的 path
。
範例
// instead of writing:
User.find({age: {$gte: 21, $lte: 65}});
// we can instead write:
User.where('age').gte(21).lte(65);
// passing query conditions is permitted
User.find().where({ name: 'vonderful' })
// chaining
User
.where('age').gte(21).lte(65)
.where('name', /^vonderful/i)
.where('friends').slice(10)
.exec()
Query.prototype.within()
傳回
- «查詢» this
參見
為地理空間查詢定義 $within
或 $geoWithin
引數。
範例
query.where(path).within().box()
query.where(path).within().circle()
query.where(path).within().geometry()
query.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true });
query.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] });
query.where('loc').within({ polygon: [[],[],[],[]] });
query.where('loc').within([], [], []) // polygon
query.where('loc').within([], []) // box
query.where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry
必須 在 where()
之後使用。
注意
從 Mongoose 3.7 開始,查詢總是使用 $geoWithin
。要更改此行為,請參閱 Query.use$geoWithin。
注意
在 Mongoose 3.7 中,within
從 getter 變更為函式。如果您需要舊的語法,請使用 此。
Query.prototype.writeConcern()
參數
writeConcern
«Object» 要設定的寫入關注值。
傳回
- «查詢» this
參見
為此查詢設定 3 個寫入關注參數。
w
:設定指定的mongod
伺服器數量,或mongod
伺服器的標籤集,這些伺服器必須先確認此寫入,此寫入才被視為成功。j
:布林值,設定為true
以請求確認此操作已持久保存到 MongoDB 的磁碟日誌。wtimeout
:如果w > 1
,則在操作失敗之前,等待此寫入在副本集中傳播的最長時間。預設值為0
,表示沒有逾時。
此選項僅適用於寫入資料庫的操作
deleteOne()
deleteMany()
findOneAndDelete()
findOneAndReplace()
findOneAndUpdate()
updateOne()
updateMany()
預設為 schema 的 writeConcern
選項
範例
// The 'majority' option means the `deleteOne()` promise won't resolve
// until the `deleteOne()` has propagated to the majority of the replica set
await mongoose.model('Person').
deleteOne({ name: 'Ned Stark' }).
writeConcern({ w: 'majority' });
Query.prototype.wtimeout()
參數
ms
«number» 等待的毫秒數。
傳回
- «查詢» this
參見
如果 w > 1
,則在操作失敗之前,等待此寫入在副本集中傳播的最長時間。預設值為 0
,表示沒有逾時。
此選項僅適用於寫入資料庫的操作
deleteOne()
deleteMany()
findOneAndDelete()
findOneAndReplace()
findOneAndUpdate()
updateOne()
updateMany()
預設為 schema 的 writeConcern.wtimeout
選項
範例
// The `deleteOne()` promise won't resolve until this `deleteOne()` has
// propagated to at least `w = 2` members of the replica set. If it takes
// longer than 1 second, this `deleteOne()` will fail.
await mongoose.model('Person').
deleteOne({ name: 'Ned Stark' }).
w(2).
wtimeout(1000);
Query.prototype[Symbol.asyncIterator]()
返回一個 asyncIterator,用於 for/await/of
迴圈。此函式僅適用於 find()
查詢。您無需顯式呼叫此函式,JavaScript 執行時會為您呼叫。
範例
for await (const doc of Model.aggregate([{ $sort: { name: 1 } }])) {
console.log(doc.name);
}
Node.js 10.x 本身支援 async iterators,無需任何標誌。您可以使用 --harmony_async_iteration
標誌在 Node.js 8.x 中啟用 async iterators。
注意:如果 Symbol.asyncIterator
未定義,則此函式將不起作用。如果 Symbol.asyncIterator
未定義,則表示您的 Node.js 版本不支援 async iterators。
Query.prototype[Symbol.toStringTag]()
傳回
- «String»
返回此查詢的字串表示。
更多關於 JavaScript 中的 toString()
。
範例
const q = Model.find();
console.log(q); // Prints "Query { find }"
Query.use$geoWithin
類型
- «property»
參見
選擇不使用 $geoWithin
的標誌。
mongoose.Query.use$geoWithin = false;
MongoDB 2.4 棄用了 $within
的使用,並以 $geoWithin
取代。Mongoose 預設使用 $geoWithin
(與 $within
100% 向後相容)。如果您執行的是較舊版本的 MongoDB,請將此標誌設定為 false
,以便您的 within()
查詢繼續工作。