Skip to content

Commit

Permalink
types: allow calling SchemaType.cast() without parent and init
Browse files Browse the repository at this point in the history
…parameters

Fix #14718
Re: #9076
  • Loading branch information
vkarpov15 committed Jul 21, 2024
1 parent e4462c6 commit 195103c
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
20 changes: 20 additions & 0 deletions test/schema.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3258,4 +3258,24 @@ describe('schema', function() {

await q;
});

it('supports casting object to subdocument (gh-14748) (gh-9076)', function() {
const nestedSchema = new Schema({ name: String });
nestedSchema.methods.getAnswer = () => 42;

const schema = new Schema({
arr: [nestedSchema],
singleNested: nestedSchema
});

// Cast to doc array
let subdoc = schema.path('arr').cast([{ name: 'foo' }])[0];
assert.ok(subdoc instanceof mongoose.Document);
assert.equal(subdoc.getAnswer(), 42);

// Cast to single nested subdoc
subdoc = schema.path('singleNested').cast({ name: 'bar' });
assert.ok(subdoc instanceof mongoose.Document);
assert.equal(subdoc.getAnswer(), 42);
});
});
15 changes: 15 additions & 0 deletions test/types/schema.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {
DefaultSchemaOptions,
HydratedArraySubdocument,
HydratedSingleSubdocument,
Schema,
Document,
Expand Down Expand Up @@ -1555,3 +1556,17 @@ function gh14696() {
});

}

function gh14748() {
const nestedSchema = new Schema({ name: String });

const schema = new Schema({
arr: [nestedSchema],
singleNested: nestedSchema
});

// Cast to single nested subdoc
const subdoc = schema.path('singleNested')
.cast<HydratedArraySubdocument<{ name: string }>>({ name: 'bar' });
expectAssignable<{ name: string }>(subdoc);
}

Check warning on line 1572 in test/types/schema.test.ts

View workflow job for this annotation

GitHub Actions / Lint TS-Files

Newline required at end of file but not found

Check warning on line 1572 in test/types/schema.test.ts

View workflow job for this annotation

GitHub Actions / Lint TS-Files

Newline required at end of file but not found
3 changes: 2 additions & 1 deletion types/schematypes.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,8 @@ declare module 'mongoose' {
OptionsConstructor: SchemaTypeOptions<T>;

/** Cast `val` to this schema type. Each class that inherits from schema type should implement this function. */
cast(val: any, doc: Document<any>, init: boolean, prev?: any, options?: any): any;
cast(val: any, doc?: Document<any>, init?: boolean, prev?: any, options?: any): any;
cast<ResultType>(val: any, doc?: Document<any>, init?: boolean, prev?: any, options?: any): ResultType;

/** Sets a default value for this SchemaType. */
default(val: any): any;
Expand Down

0 comments on commit 195103c

Please sign in to comment.