diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index f08b8e0b5c..ad515a1806 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -2021,6 +2021,30 @@ declare module "mongoose" { */ or(array: any[]): this; + /** + * Make this query throw an error if no documents match the given `filter`. + * This is handy for integrating with async/await, because `orFail()` saves you + * an extra `if` statement to check if no document was found. + * + * ####Example: + * + * // Throws if no doc returned + * await Model.findOne({ foo: 'bar' }).orFail(); + * + * // Throws if no document was updated + * 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')); + * + * @param err optional error to throw if no docs match `filter` + */ + orFail(err?: Error | (() => Error)): this; + /** Specifies a $polygon condition */ polygon(...coordinatePairs: number[][]): this; polygon(path: string, ...coordinatePairs: number[][]): this; diff --git a/types/mongoose/mongoose-tests.ts b/types/mongoose/mongoose-tests.ts index a660ce728f..f4fec31101 100644 --- a/types/mongoose/mongoose-tests.ts +++ b/types/mongoose/mongoose-tests.ts @@ -1080,6 +1080,7 @@ query.find().where('age').in([20, 21]); query.find().in('age', [20, 21]); query.nor([{ color: 'green' }, { status: 'ok' }]).nor([]); query.or([{ color: 'red' }, { status: 'emergency' }]).or([]); +query.find({ color: 'blue' }).orFail(); query.where('loc').within().polygon([10,20], [13, 25], [7,15]); query.polygon('loc', [10,20], [13, 25], [7,15]); query.findOne().populate('owner').exec(function (err, kitten) {