From b645f4e7cc16192b942533f692c96d2cb2e71474 Mon Sep 17 00:00:00 2001 From: Valentin Agachi Date: Mon, 9 Mar 2020 17:55:38 +0000 Subject: [PATCH] [mongoose] Define lean() result type (#42652) --- types/mongoose/index.d.ts | 8 +++++- types/mongoose/mongoose-tests.ts | 43 +++++++++++++++++++++++++++----- 2 files changed, 44 insertions(+), 7 deletions(-) diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index 2f05cfa52f..71b03c3eda 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -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 = Pick>; + + /* Helper type to extract a definition type from a Document type */ + type DocumentDefinition = Omit & { _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

(bool?: boolean | object): Query ? P[] : (P | null)> & QueryHelpers; + lean

>(bool?: boolean | object): Query ? P[] : (P | null)> & QueryHelpers; /** Specifies the maximum number of documents the query will return. Cannot be used with distinct() */ limit(val: number): this; diff --git a/types/mongoose/mongoose-tests.ts b/types/mongoose/mongoose-tests.ts index c6537de18d..d864af7e89 100644 --- a/types/mongoose/mongoose-tests.ts +++ b/types/mongoose/mongoose-tests.ts @@ -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 = >{}; +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) {