Skip to content

Schema.create() for TypeScript type inference #15482

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 17 commits into
base: 9.0
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions lib/schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,29 @@ Schema.prototype.paths;

Schema.prototype.tree;

/**
* Creates a new schema with the given definition and options. Equivalent to `new Schema(definition, options)`.
*
* `Schema.create()` is primarily useful for automatic schema type inference in TypeScript.
*
* #### Example:
*
* const schema = Schema.create({ name: String }, { toObject: { virtuals: true } });
* // Equivalent:
* const schema2 = new Schema({ name: String }, { toObject: { virtuals: true } });
*
* @param {Object} definition
* @param {Object} [options]
* @return {Schema} the new schema
* @api public
* @memberOf Schema
* @static
*/

Schema.create = function create(definition, options) {
return new Schema(definition, options);
};

/**
* Returns a deep copy of the schema
*
Expand Down
4 changes: 2 additions & 2 deletions test/types/inferrawdoctype.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { InferRawDocType } from 'mongoose';
import { InferRawDocType, Types } from 'mongoose';
import { expectType, expectError } from 'tsd';

function gh14839() {
Expand All @@ -21,5 +21,5 @@ function gh14839() {
};

type UserType = InferRawDocType< typeof schemaDefinition>;
expectType<{ email: string, password: string, dateOfBirth: Date }>({} as UserType);
expectType<{ email: string, password: string, dateOfBirth: Date } & { _id: Types.ObjectId }>({} as UserType);
}
Loading
Loading