diff --git a/index.d.ts b/index.d.ts index a4a2f28a70b..0593c30015d 100644 --- a/index.d.ts +++ b/index.d.ts @@ -472,10 +472,10 @@ declare module "mongoose" { set(value: any): this; /** The return value of this method is used in calls to JSON.stringify(doc). */ - toJSON(options?: ToObjectOptions): any; + toJSON(options?: ToObjectOptions): LeanDocument; /** Converts this document into a plain-old JavaScript object ([POJO](https://masteringjs.io/tutorials/fundamentals/pojo)). */ - toObject(options?: ToObjectOptions): any; + toObject(options?: ToObjectOptions): LeanDocument; /** Clears the modified state on the specified path. */ unmarkModified(path: string); @@ -1480,7 +1480,7 @@ declare module "mongoose" { j(val: boolean | null): this; /** Sets the lean option. */ - lean(val?: boolean | any): this; + lean(val?: boolean | any): Query, DocType>; /** Specifies the maximum number of documents the query will return. */ limit(val: number): this; @@ -1702,7 +1702,9 @@ declare module "mongoose" { export type UpdateQuery = mongodb.UpdateQuery & mongodb.MatchKeysAndValues; - export type DocumentDefinition = Omit> + export type DocumentDefinition = Omit>; + + export type LeanDocument = Omit>; class QueryCursor extends stream.Readable { /** diff --git a/test/typescript/leanDocuments.ts b/test/typescript/leanDocuments.ts new file mode 100644 index 00000000000..0f72217e1a9 --- /dev/null +++ b/test/typescript/leanDocuments.ts @@ -0,0 +1,23 @@ +import { Schema, model, Document, Types } from 'mongoose'; + +const schema: Schema = new Schema({ name: { type: 'String' } }); + +interface ITest extends Document { + _id?: Types.ObjectId, + name?: string; +} + +const Test = model('Test', schema); + +void async function main() { + const doc: ITest = await Test.findOne(); + + const pojo = doc.toObject(); + await pojo.save(); + + const _doc = await Test.findOne().lean(); + await _doc.save(); + + const hydrated = Test.hydrate(_doc); + await hydrated.save(); +}(); \ No newline at end of file diff --git a/test/typescript/main.test.js b/test/typescript/main.test.js index d09140367ee..b9bb974f77a 100644 --- a/test/typescript/main.test.js +++ b/test/typescript/main.test.js @@ -119,6 +119,16 @@ describe('typescript syntax', function() { } assert.equal(errors.length, 0); }); + + it('lean documents', function() { + const errors = runTest('leanDocuments.ts'); + if (process.env.D && errors.length) { + console.log(errors); + } + assert.equal(errors.length, 2); + assert.ok(errors[0].messageText.includes('Property \'save\' does not exist'), errors[0].messageText); + assert.ok(errors[1].messageText.includes('Property \'save\' does not exist'), errors[0].messageText); + }); }); function runTest(file) {