Skip to content
This repository has been archived by the owner on Jun 29, 2021. It is now read-only.

Commit

Permalink
Add the possibility to use instance methods in sub schemas (#199)
Browse files Browse the repository at this point in the history
Add the possibility to use instance methods in sub schemas
  • Loading branch information
cjanietz authored and Ben305 committed Feb 4, 2019
1 parent 3496dcc commit 9141ed9
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 3 deletions.
11 changes: 9 additions & 2 deletions src/prop.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as mongoose from 'mongoose';
import * as _ from 'lodash';

import { schema, virtuals } from './data';
import { schema, virtuals, methods } from './data';
import { isPrimitive, initAsObject, initAsArray, isString, isNumber, isObject } from './utils';
import { InvalidPropError, NotNumberTypeError, NotStringTypeError, NoMetadataError } from './errors';
import { ObjectID } from 'bson';
Expand Down Expand Up @@ -181,10 +181,17 @@ const baseProp = (rawOptions, Type, target, key, isArray = false) => {
const Schema = mongoose.Schema;

const supressSubschemaId = rawOptions._id === false;
const virtualSchema = new Schema({ ...subSchema }, supressSubschemaId ? { _id: false } : {});

const schemaInstanceMethods = methods.instanceMethods[instance.constructor.name];
if (schemaInstanceMethods) {
virtualSchema.methods = schemaInstanceMethods;
}

schema[name][key] = {
...schema[name][key],
...options,
type: new Schema({ ...subSchema }, supressSubschemaId ? { _id: false } : {}),
type: virtualSchema,
};
return;
};
Expand Down
1 change: 1 addition & 0 deletions src/test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ describe('Typegoose', () => {
expect(foundUser.job).to.have.property('position', 'Lead');
expect(foundUser.job).to.have.property('startedAt').to.be.instanceof(Date);
expect(foundUser.job.jobType).to.not.have.property('_id');
expect(foundUser.job.titleInUppercase()).to.eq("Developer".toUpperCase());
expect(foundUser.job.jobType).to.have.property('salery', 5000);
expect(foundUser.job.jobType).to.have.property('field', 'IT');
expect(foundUser.job.jobType).to.have.property('salery').to.be.a('number');
Expand Down
7 changes: 6 additions & 1 deletion src/test/models/job.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { prop } from '../../typegoose';
import { instanceMethod, prop } from '../../typegoose';

export class JobType {
@prop({ required: true })
Expand All @@ -20,4 +20,9 @@ export class Job {

@prop({ _id: false })
jobType?: JobType;

@instanceMethod
titleInUppercase?() {
return this.title.toUpperCase();
}
}

0 comments on commit 9141ed9

Please sign in to comment.