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]
«Object»[model]
«Object»[conditions]
«Object»[collection]
«Object» Mongooseコレクション
クエリを構築するために使用される Query コンストラクター。 Query
を直接インスタンス化する必要はありません。代わりに Model.find()
のような Model 関数を使用してください。
例
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
«String|Function» JavaScript文字列または関数
戻り値
- «Query» 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;
})
注意
$lt
のような他の MongoDB 演算子を使用して満たすことができない条件がある場合にのみ、$where
を使用してください。使用する前に、そのすべての注意点について必ずお読みください。
Query.prototype.all()
パラメーター
[path]
«String»val
«Array»
参照
$all
クエリ条件を指定します。
引数 1 つで呼び出された場合、where()
に渡された最新のパスが使用されます。
例
MyModel.find().where('pets').all(['dog', 'cat', 'ferret']);
// Equivalent:
MyModel.find().all('pets', ['dog', 'cat', 'ferret']);
Query.prototype.allowDiskUse()
パラメーター
[v]
«Boolean»allowDiskUse
を有効/無効にします。引数なしで呼び出すと、allowDiskUse: true
を設定します。
戻り値
- «Query» 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
«Array» 条件の配列
戻り値
- «Query» this
参照
Query.prototype.batchSize()
パラメーター
val
«Number»
参照
Query.prototype.box()
パラメーター
val1
«Object|Array<Number>» 左下座標または左下 (ll) と右上 (ur) 座標のオブジェクト[val2]
«Array<Number>» 右上座標
戻り値
- «Query» 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]
«Model» キャスト先のモデル。設定されていない場合、デフォルトでthis.model
になります[obj]
«Object»
戻り値
- «Object»
Query.prototype.catch()
パラメーター
[reject]
«Function»
戻り値
- «Promise»
クエリを実行し、ドキュメントで解決されるか、エラーで拒否される Promise
を返します。.then()
と同様ですが、拒否ハンドラーのみを受け取ります。
JavaScript での Promise catch()
について詳しくはこちらをご覧ください。
Query.prototype.center()
~非推奨~Query.prototype.centerSphere()
~非推奨~パラメーター
[path]
«String»val
«Object»
戻り値
- «Query» this
参照
非推奨 $centerSphere
条件を指定します
非推奨。代わりに circle を使用してください。
例
const area = { center: [50, 50], radius: 10 };
query.where('loc').within().centerSphere(area);
Query.prototype.circle()
パラメーター
[path]
«String»area
«Object»
戻り値
- «Query» 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()
戻り値
- «Query» コピー
このクエリのコピーを作成して、再実行できるようにします。
例
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
«Object»
戻り値
- «Query» this
参照
この操作に照合を追加します (MongoDB 3.4 以降)
Query.prototype.comment()
パラメーター
val
«String»
参照
Query.prototype.countDocuments()
パラメーター
[filter]
«Object» mongodb セレクター[options]
«Object»
戻り値
- «Query» 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]
«Object»
戻り値
- «QueryCursor»
参照
mongodb ドライバーカーソルのラッパーを返します。QueryCursor は Streams3 インターフェイスと .next()
関数を公開します。
.cursor()
関数は、事前検索フックをトリガーしますが、事後検索フックはトリガーしません。
例
// 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]
«Object|Query» mongodb セレクター[options]
«Object» オプションの参照:Query.prototype.setOptions()
戻り値
- «Query» this
参照
このクエリを deleteMany()
操作として宣言および/または実行します。remove と同様に動作しますが、single
の値に関係なく、コレクション内の filter
に一致するすべてのドキュメントを削除するという点が異なります。
この関数は 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]
«Object|Query» mongodb セレクター[options]
«Object» オプションの参照:Query.prototype.setOptions()
戻り値
- «Query» this
参照
このクエリを deleteOne()
操作として宣言および/または実行します。remove と同様に動作しますが、single
オプションに関係なく、最大で 1 つのドキュメントを削除するという点が異なります。
この関数は 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]
«String»[filter]
«Object|Query»[options]
«Object»
戻り値
- «Query» this
参照
distinct() 操作を宣言または実行します。
この関数はミドルウェアをトリガーしません。
例
distinct(field, conditions, options)
distinct(field, conditions)
distinct(field)
distinct()
Query.prototype.elemMatch()
パラメーター
path
«String|Object|Function»filter
«Object|Function»
戻り値
- «Query» 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
«Object»
戻り値
- «Query» this
where()
で指定されたパスの補完的な比較値を指定します
例
User.where('age').equals(49);
// is the same as
User.where('age', 49);
Query.prototype.error()
パラメーター
err
«Error|null» 設定されている場合、exec()
は MongoDB にクエリを送信する前に即座に失敗します
戻り値
- «Query» 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]
«Object» MongoDB ドライバーに透過的に渡されます
戻り値
- «Query» this
参照
このクエリをestimatedDocumentCount()
クエリとして指定します。estimatedDocumentCount()
はコレクション全体をスキャンするのではなく、コレクションのメタデータを使用するため、大規模なコレクションではcountDocuments()
を使用するよりも高速です。
estimatedDocumentCount()
は、フィルターを受け付けません。Model.find({ foo: bar }).estimatedDocumentCount()
はModel.find().estimatedDocumentCount()
と同等です。
この関数は、次のミドルウェアをトリガーします。
estimatedDocumentCount()
例
await Model.find().estimatedDocumentCount();
Query.prototype.exec()
パラメーター
[operation]
«String|Function»
戻り値
- «Promise»
Query.prototype.exists()
パラメーター
[path]
«String»val
«Boolean»
戻り値
- «Query» 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' です。
戻り値
- «Query» 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»
.finally()
がチェーンされたPromise
を返してクエリを実行します。
Query.prototype.find()
パラメーター
[filter]
«Object|ObjectId» mongodbフィルター。指定しない場合は、すべてのドキュメントを返します。
戻り値
- «Query» this
selector
に一致するすべてのドキュメントを検索します。結果はドキュメントの配列になります。
結果に含まれるドキュメントが多すぎてメモリに収まらない場合は、Query.prototype.cursor()
を使用してください。
例
const arr = await Movie.find({ year: { $gte: 1980, $lte: 1989 } });
Query.prototype.findOne()
パラメーター
[filter]
«Object» mongodb セレクター[projection]
«Object» 返すオプションのフィールド[options]
«Object»setOptions()
を参照してください[options.translateAliases=null]
«Boolean»true
に設定すると、filter
、projection
、update
、およびdistinct
でスキーマで定義されたエイリアスを変換します。エイリアスと生のプロパティの両方が同じオブジェクトで定義されている競合がある場合は、エラーをスローします。
戻り値
- «Query» this
参照
クエリをfindOne操作として宣言します。実行されると、最初に見つかったドキュメントがコールバックに渡されます。
クエリの結果は、単一のドキュメント、またはドキュメントが見つからない場合はnull
になります。
- 注:
conditions
はオプションであり、conditions
がnullまたは未定義の場合、mongooseは空のfindOne
コマンドをMongoDBに送信します。これにより、任意のドキュメントが返されます。_id
でクエリを実行している場合は、代わりにModel.findById()
を使用してください。
この関数は、次のミドルウェアをトリガーします。
findOne()
例
const query = Kitten.where({ color: 'white' });
const kitten = await query.findOne();
Query.prototype.findOneAndDelete()
パラメーター
[filter]
«Object»[options]
«Object»[options.includeResultMetadata]
«Boolean» trueの場合、ドキュメントだけでなく、MongoDBドライバーからの完全なModifyResultを返します[options.session=null]
«ClientSession» このクエリに関連付けられたセッション。トランザクションドキュメントを参照してください。[options.strict]
«Boolean|String» スキーマのstrictモードオプションを上書きします
戻り値
- «Query» 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]
«Object»[options.includeResultMetadata]
«Boolean» trueの場合、ドキュメントだけでなく、MongoDBドライバーからの完全なModifyResultを返します[options.session=null]
«ClientSession» このクエリに関連付けられたセッション。トランザクションドキュメントを参照してください。[options.strict]
«Boolean|String» スキーマのstrictモードオプションを上書きします[options.new=false]
«Boolean» デフォルトでは、findOneAndUpdate()
は、update
が適用される前のドキュメントを返します。new: true
を設定すると、findOneAndUpdate()
は代わりにupdate
が適用された後のオブジェクトを提供します。[options.lean]
«Object» truthyの場合、mongooseはドキュメントをmongooseドキュメントではなく、プレーンなJavaScriptオブジェクトとして返します。Query.lean()
とMongoose leanチュートリアルを参照してください。[options.session=null]
«ClientSession» このクエリに関連付けられたセッション。トランザクションドキュメントを参照してください。[options.strict]
«Boolean|String» スキーマのstrictモードオプションを上書きします[options.timestamps=null]
«Boolean»false
に設定し、スキーマレベルのタイムスタンプが有効になっている場合は、この更新のタイムスタンプをスキップします。これにより、タイムスタンプを上書きできることに注意してください。スキーマレベルのタイムスタンプが設定されていない場合は何も行いません。[options.returnOriginal=null]
«Boolean»new
オプションのエイリアス。returnOriginal: false
はnew: true
と同等です。[options.translateAliases=null]
«Boolean»true
に設定すると、filter
、projection
、update
、およびdistinct
でスキーマで定義されたエイリアスを変換します。エイリアスと生のプロパティの両方が同じオブジェクトで定義されている競合がある場合は、エラーをスローします。
戻り値
- «Query» 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]
«Object|Query»[doc]
«Object»[options]
«Object»[options.includeResultMetadata]
«Boolean» trueの場合、ドキュメントだけでなく、MongoDBドライバーからの完全なModifyResultを返します[options.strict]
«Boolean|String» スキーマのstrictモードオプションを上書きします[options.session=null]
«ClientSession» このクエリに関連付けられたセッション。トランザクションドキュメントを参照してください。[options.multipleCastError]
«Boolean» デフォルトでは、mongooseはクエリのキャストで発生した最初のエラーのみを返します。このオプションをオンにして、すべてのキャストエラーを集計します。[options.new=false]
«Boolean» デフォルトでは、findOneAndUpdate()
は、update
が適用される前のドキュメントを返します。new: true
を設定すると、findOneAndUpdate()
は代わりにupdate
が適用された後のオブジェクトを提供します。[options.lean]
«Object» truthyの場合、mongooseはドキュメントをmongooseドキュメントではなく、プレーンなJavaScriptオブジェクトとして返します。Query.lean()
とMongoose leanチュートリアルを参照してください。[options.session=null]
«ClientSession» このクエリに関連付けられたセッション。トランザクションドキュメントを参照してください。[options.strict]
«Boolean|String» スキーマのstrictモードオプションを上書きします[options.timestamps=null]
«Boolean»false
に設定し、スキーマレベルのタイムスタンプが有効になっている場合は、この更新のタイムスタンプをスキップします。これにより、タイムスタンプを上書きできることに注意してください。スキーマレベルのタイムスタンプが設定されていない場合は何も行いません。[options.returnOriginal=null]
«Boolean»new
オプションのエイリアス。returnOriginal: false
はnew: true
と同等です。[options.translateAliases=null]
«Boolean»true
に設定すると、filter
、projection
、update
、およびdistinct
でスキーマで定義されたエイリアスを変換します。エイリアスと生のプロパティの両方が同じオブジェクトで定義されている競合がある場合は、エラーをスローします。[options.overwriteDiscriminatorKey=false]
«Boolean» Mongooseはデフォルトでupdate
からdiscriminatorキーの更新を削除します。discriminatorキーの更新を許可するには、overwriteDiscriminatorKey
をtrue
に設定します
戻り値
- «Query» 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の場合、このコマンドで更新バリデーターを実行します。更新バリデーターは、モデルのスキーマに対して更新操作を検証します。setDefaultsOnInsert
:デフォルトではtrue
です。setDefaultsOnInsert
とupsert
がtrueの場合、新しいドキュメントが作成された場合に、mongooseはモデルのスキーマで指定されたデフォルトを適用します。
例
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
プロパティ(String)とcoordinates
プロパティ(Array)を含む必要があります。例を参照してください。
戻り値
- «Query» 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» 取得するパスまたはキー/値ペアのオブジェクト
戻り値
- «Query» this
更新操作の場合、更新の$set
内のパスの値を返します。更新操作とsave()
の両方で機能できるゲッター/セッターを記述するのに役立ちます。
例
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()
と同等です。
可能な場合は、getQuery()
ではなくgetFilter()
を使用する必要があります。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]
«String»val
«Number»
参照
$gt
クエリ条件を指定します。
引数 1 つで呼び出された場合、where()
に渡された最新のパスが使用されます。
例
Thing.find().where('age').gt(21);
// or
Thing.find().gt('age', 21);
Query.prototype.gte()
パラメーター
[path]
«String»val
«Number»
参照
$gte
クエリ条件を指定します。
引数 1 つで呼び出された場合、where()
に渡された最新のパスが使用されます。
Query.prototype.hint()
パラメーター
val
«Object» ヒントオブジェクト
戻り値
- «Query» this
参照
Query.prototype.in()
パラメーター
[path]
«String»val
«Array»
参照
$in
クエリ条件を指定します。
引数 1 つで呼び出された場合、where()
に渡された最新のパスが使用されます。
Query.prototype.intersects()
パラメーター
[arg]
«Object»
戻り値
- «Query» this
参照
geometry()
のintersectsクエリを宣言します。
例
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
はゲッターから関数に変更されました。古い構文が必要な場合は、こちらを使用してください。
Query.prototype.isPathSelectedInclusive()
パラメーター
path
«String»
戻り値
- «Boolean»
クエリでisPathSelectedInclusiveを呼び出すためのラッパー関数。
Query.prototype.j()
パラメーター
val
«boolean»
戻り値
- «Query» this
参照
この操作がMongoDBのディスク上のジャーナルに保持されたことの確認を要求します。このオプションは、データベースに書き込む操作に対してのみ有効です。
deleteOne()
deleteMany()
findOneAndDelete()
findOneAndReplace()
findOneAndUpdate()
updateOne()
updateMany()
デフォルトは、スキーマのwriteConcern.j
オプションです
例
await mongoose.model('Person').deleteOne({ name: 'Ned Stark' }).j(true);
Query.prototype.lean()
パラメーター
bool
«Boolean|Object» デフォルトはtrue
戻り値
- «Query» this
leanオプションを設定します。
lean
オプションが有効になっているクエリから返されるドキュメントは、Mongooseドキュメントではなく、プレーンなJavaScriptオブジェクトです。これらには、save
メソッド、ゲッター/セッター、バーチャル、またはその他の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()
でバーチャル、ゲッター/セッター、またはデフォルトが必要な場合は、プラグインを使用する必要があります。参照
Query.prototype.limit()
パラメーター
val
«Number»
Query.prototype.lt()
パラメーター
[path]
«String»val
«Number»
参照
$lt
クエリ条件を指定します。
引数 1 つで呼び出された場合、where()
に渡された最新のパスが使用されます。
Query.prototype.lte()
パラメーター
[path]
«String»val
«Number»
参照
$lte
クエリ条件を指定します。
引数 1 つで呼び出された場合、where()
に渡された最新のパスが使用されます。
Query.prototype.maxDistance()
パラメーター
[path]
«String»val
«Number»
参照
maxDistance
クエリ条件を指定します。
引数 1 つで呼び出された場合、where()
に渡された最新のパスが使用されます。
Query.prototype.maxTimeMS()
パラメーター
[ms]
«Number» ミリ秒単位の数値
戻り値
- «Query» this
maxTimeMSオプションを設定します。これにより、クエリまたは書き込み操作がms
ミリ秒を超えて実行されている場合、MongoDBサーバーに中止するように指示します。
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»
戻り値
- «Query» this
別のクエリまたは条件オブジェクトをこのクエリにマージします。
クエリが渡されると、条件、フィールド選択、およびオプションがマージされます。
Query.prototype.mod()
パラメーター
[path]
«String»val
«Array» は長さ 2 でなければなりません。最初の要素はdivisor
、2 番目の要素はremainder
です。
戻り値
- «Query» 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 固有のオプションを操作するゲッター/セッター。以下は現在の Mongoose 固有のオプションです。
populate
: どのパスがポピュレートされるかを表す配列。Query.prototype.populate()
の各呼び出しに対して 1 つのエントリが必要です。lean
: truthy の場合、Mongoose はこのクエリから返されたドキュメントを ハイドレート しません。詳細については、Query.prototype.lean()
を参照してください。strict
: Mongoose がスキーマにないキーを更新でどのように処理するかを制御します。このオプションはデフォルトでtrue
です。つまり、Mongoose はスキーマにない更新のパスをすべて自動的に削除します。詳細については、strict
モードのドキュメントを参照してください。strictQuery
: Mongoose がクエリのfilter
に対してスキーマにないキーをどのように処理するかを制御します。このオプションはデフォルトでfalse
です。つまり、foo
がスキーマになくても、Mongoose はModel.find({ foo: 'bar' })
を許可します。詳細については、strictQuery
のドキュメントを参照してください。nearSphere
:near()
の代わりに$nearSphere
を使用します。Query.prototype.nearSphere()
のドキュメントを参照してください。
Mongoose は内部オプション用に別のオブジェクトを保持しています。これは Mongoose が Query.prototype.options
を MongoDB サーバーに送信するためであり、上記のオプションは MongoDB サーバーには関係がないためです。
Query.prototype.ne()
パラメーター
[path]
«String»val
«any»
参照
$ne
クエリ条件を指定します。
引数 1 つで呼び出された場合、where()
に渡された最新のパスが使用されます。
Query.prototype.near()
パラメーター
[path]
«String»val
«Object»
戻り値
- «Query» 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 });
非推奨。 spherical
オプションを true
に設定して query.near()
を代わりに使用してください。
例
query.where('loc').near({ center: [10, 10], spherical: true });
Query.prototype.nin()
パラメーター
[path]
«String»val
«Array»
参照
$nin
クエリ条件を指定します。
引数 1 つで呼び出された場合、where()
に渡された最新のパスが使用されます。
Query.prototype.nor()
パラメーター
array
«Array» 条件の配列
戻り値
- «Query» this
参照
Query.prototype.or()
パラメーター
array
«Array» 条件の配列
戻り値
- «Query» this
参照
Query.prototype.orFail()
パラメーター
[err]
«Function|Error» オプション。filter
に一致するドキュメントがない場合にスローされるエラー。指定されていない場合、orFail()
はDocumentNotFoundError
をスローします。
戻り値
- «Query» 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»
戻り値
- «Query» 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» ポピュレーションに使用するモデル。指定されていない場合、ポピュレートはスキーマの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
で定義されたゲッターを呼び出します。デフォルトでは、Mongoose はlocalField
の生の値を取得します。たとえば、localField
にlowercase
ゲッターを追加する場合は、このオプションをtrue
に設定する必要があります。[options.clone=false]
«boolean»BlogPost.find().populate('author')
を実行すると、同じ作成者のブログ投稿はauthor
ドキュメントの 1 つのコピーを共有します。このオプションを有効にすると、Mongoose はポピュレートされたドキュメントを割り当てる前に複製します。[options.match=null]
«Object|Function» ポピュレーションクエリに追加のフィルターを追加します。MongoDB クエリ構文を含むフィルターオブジェクト、またはフィルターオブジェクトを返す関数を指定できます。[options.transform=null]
«Function» Mongoose がポピュレートされたすべてのドキュメントで呼び出す関数。ポピュレートされたドキュメントを変換できます。[options.options=null]
«Object»limit
やlean
などの追加オプション。
戻り値
- «Query» 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» このクエリのオプションのタグ。
戻り値
- «Query» 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» リストされた読み取り懸念レベルまたはそのエイリアスのいずれか。
戻り値
- «Query» 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]
«String»val
«String|RegExp»
参照
$regex
クエリ条件を指定します。
引数 1 つで呼び出された場合、where()
に渡された最新のパスが使用されます。
Query.prototype.replaceOne()
パラメーター
[filter]
«Object»[doc]
«Object» 更新コマンド。[options]
«Object»[options.multipleCastError]
«Boolean» デフォルトでは、mongooseはクエリのキャストで発生した最初のエラーのみを返します。このオプションをオンにして、すべてのキャストエラーを集計します。[options.strict]
«Boolean|String» スキーマの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) です。
戻り値
- «Query» 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»
戻り値
- «Query» this
参照
このクエリの sanitizeProjection
オプションを設定します。設定されている場合、sanitizeProjection
は 2 つのことを実行します。
- プロジェクション値が文字列ではなく数値であることを強制します。
- デフォルトで選択解除されているプロパティを上書きするために
+
構文を使用することを防ぎます。
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]»
戻り値
- «Query» 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()
から
戻り値
- «Query» 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» 設定する値。
戻り値
- «Query» 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»
戻り値
- «Query» this
クエリオプションを設定します。一部のオプションは、特定の操作に対してのみ意味を持ちます。
オプション
以下のオプションは find()
のみで使用できます。
以下のオプションは、書き込み操作 (updateOne()
、updateMany()
、replaceOne()
、findOneAndUpdate()
、および findByIdAndUpdate()
) のみで使用できます。
- upsert
- writeConcern
- タイムスタンプ: スキーマに
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]
«String»val
«Number»
参照
$size
クエリ条件を指定します。
引数 1 つで呼び出された場合、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
«Number»
参照
Query.prototype.slice()
パラメーター
[path]
«String»val
«Number|Array» スライスする要素数、またはスキップする要素数とスライスする要素数を含む配列
戻り値
- «Query» 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]
«Object»[options.override=false]
«Boolean» trueの場合、既存のソートオプションをarg
で置き換えます
戻り値
- «Query» 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]
«Function»
戻り値
- «Promise»
クエリを実行し、ドキュメントで解決されるか、エラーで拒否される Promise
を返します。
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» クエリ結果を変換するために実行する関数
戻り値
- «Query» this
関数 fn
を実行し、 fn
の戻り値を、解決されるクエリの新しい値として扱います。
transform()
に渡す関数は、すべてポストフック後に実行されます。
例
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]
«Object»[options.multipleCastError]
«Boolean» デフォルトでは、mongooseはクエリのキャストで発生した最初のエラーのみを返します。このオプションをオンにして、すべてのキャストエラーを集計します。[options.strict]
«Boolean|String» スキーマの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
からdiscriminatorキーの更新を削除します。discriminatorキーの更新を許可するには、overwriteDiscriminatorKey
をtrue
に設定します[callback]
«Function» パラメーターは (error, writeOpResult) です。
戻り値
- «Query» 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]
«Object»[options.multipleCastError]
«Boolean» デフォルトでは、mongooseはクエリのキャストで発生した最初のエラーのみを返します。このオプションをオンにして、すべてのキャストエラーを集計します。[options.strict]
«Boolean|String» スキーマの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
からdiscriminatorキーの更新を削除します。discriminatorキーの更新を許可するには、overwriteDiscriminatorKey
をtrue
に設定します[callback]
«Function» パラメーターは (error, writeOpResult) です。
戻り値
- «Query» 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、1つのサーバーによって承認された場合は1、レプリカセットの大部分の場合は'majority'、またはより高度なオプションのいずれか。
戻り値
- «Query» this
参照
書き込みが成功したとみなされる前に、この書き込みを承認する必要がある指定された数の mongod
サーバー、または mongod
サーバーのタグセットを設定します。このオプションは、データベースに書き込む操作でのみ有効です
deleteOne()
deleteMany()
findOneAndDelete()
findOneAndReplace()
findOneAndUpdate()
updateOne()
updateMany()
スキーマの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»
戻り値
- «Query» 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()
戻り値
- «Query» 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
がゲッターから関数に変更されました。古い構文が必要な場合は、こちらを使用してください。
Query.prototype.writeConcern()
パラメーター
writeConcern
«Object» 設定する書き込み保証値
戻り値
- «Query» this
参照
このクエリの3つの書き込み保証パラメータを設定します
w
: 書き込みが成功したとみなされる前に、この書き込みを承認する必要がある指定された数のmongod
サーバー、またはmongod
サーバーのタグセットを設定します。j
: ブール値。true
に設定すると、この操作がMongoDBのオンディスクジャーナルに永続化されたことを確認するリクエストになります。wtimeout
:w > 1
の場合、この操作が失敗する前に、この書き込みがレプリカセット全体に伝播するのを待つ最大時間。デフォルトは0
で、これはタイムアウトがないことを意味します。
このオプションは、データベースに書き込む操作でのみ有効です
deleteOne()
deleteMany()
findOneAndDelete()
findOneAndReplace()
findOneAndUpdate()
updateOne()
updateMany()
スキーマの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» 待機するミリ秒数
戻り値
- «Query» this
参照
w > 1
の場合、この操作が失敗する前に、この書き込みがレプリカセット全体に伝播するのを待つ最大時間。デフォルトは 0
で、これはタイムアウトがないことを意味します。
このオプションは、データベースに書き込む操作でのみ有効です
deleteOne()
deleteMany()
findOneAndDelete()
findOneAndReplace()
findOneAndUpdate()
updateOne()
updateMany()
スキーマの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]()
for/await/of
ループで使用するためのasyncIteratorを返します。この関数は find()
クエリのみで機能します。この関数を明示的に呼び出す必要はありません。JavaScriptランタイムが自動的に呼び出します。
例
for await (const doc of Model.aggregate([{ $sort: { name: 1 } }])) {
console.log(doc.name);
}
Node.js 10.xは、フラグなしでasyncイテレータをネイティブにサポートします。 --harmony_async_iteration
フラグを使用して、Node.js 8.xでasyncイテレータを有効にできます。
注: この関数は Symbol.asyncIterator
が未定義の場合は使用できません。 Symbol.asyncIterator
が未定義の場合、それはNode.jsのバージョンがasyncイテレータをサポートしていないことを意味します。
Query.prototype[Symbol.toStringTag]()
戻り値
- «String»
Query.use$geoWithin
型
- «property»
参照
$geoWithin
の使用をオプトアウトするためのフラグ。
mongoose.Query.use$geoWithin = false;
MongoDB 2.4は $within
の使用を非推奨にし、$geoWithin
に置き換えました。Mongooseはデフォルトで $geoWithin
を使用します(これは $within
と100%下位互換性があります)。古いバージョンのMongoDBを実行している場合は、このフラグを false
に設定して、within()
クエリが引き続き機能するようにしてください。