[mongoose] Define lean() result type (#42652)

This commit is contained in:
Valentin Agachi
2020-03-09 17:55:38 +00:00
committed by GitHub
parent d569b92b7a
commit b645f4e7cc
2 changed files with 44 additions and 7 deletions

View File

@@ -75,6 +75,12 @@ declare module "mongoose" {
import stream = require('stream');
import mongoose = require('mongoose');
// We can use TypeScript Omit once minimum required TypeScript Version is above 3.5
type Omit<T, K> = Pick<T, Exclude<keyof T, K>>;
/* Helper type to extract a definition type from a Document type */
type DocumentDefinition<T> = Omit<T, keyof Document> & { _id: mongodb.ObjectId };
/**
* Gets and optionally overwrites the function used to pluralize collection names
* @param fn function to use for pluralization of collection names
@@ -2042,7 +2048,7 @@ declare module "mongoose" {
* getters/setters or other Mongoose magic applied.
* @param {Boolean|Object} bool defaults to true
*/
lean<P = any>(bool?: boolean | object): Query<T extends Array<any> ? P[] : (P | null)> & QueryHelpers;
lean<P = DocumentDefinition<DocType>>(bool?: boolean | object): Query<T extends Array<any> ? P[] : (P | null)> & QueryHelpers;
/** Specifies the maximum number of documents the query will return. Cannot be used with distinct() */
limit(val: number): this;

View File

@@ -1302,6 +1302,29 @@ query.lean() // true
query.lean(false)
query.lean({})
interface Location1 extends mongoose.Document {
name: string;
address: string;
rating: number;
reviews: any[];
};
var locQuery = <mongoose.DocumentQuery<Location1, Location1>>{};
async function leanTests() {
var location = await locQuery.lean().exec();
if (location) {
// $ExpectType ObjectId
location._id;
// $ExpectType string
location.name;
// $ExpectType number
location.rating;
// $ExpectError
location.unknown;
// $ExpectError
location.save();
}
}
/*
* section schema/array.js
* http://mongoosejs.com/docs/api.html#schema-array-js
@@ -1829,12 +1852,6 @@ interface ModelUser {
name: string;
abctest: string;
}
MongoModel.findOne({ type: 'iphone' }).select('name').lean().exec()
.then(function(doc: ModelUser) {
doc._id;
doc.name;
doc.abctest;
});
MongoModel.findOneAndRemove({}, {}, cb);
MongoModel.findOneAndRemove({}, {});
MongoModel.findOneAndRemove({}, cb);
@@ -2026,6 +2043,20 @@ LocModel.findOne({}, function (err, doc) {
doc.openingTimes;
}
});
LocModel
.findOne({ name: 'foo' })
.lean()
.exec()
.then(function(doc) {
if (doc) {
// $ExpectType ObjectId
doc._id;
// $ExpectType string
doc.name;
// $ExpectError
doc.unknown;
}
});
LocModel.findOneAndRemove()
.exec(function (err, location) {
if (location) {