profile
viewpoint
hasezoey hasezoey Germany https://gitlab.com/hasezoey Typescript & Rust developer

nodkz/mongodb-memory-server 1249

Spinning up mongod in memory for fast tests. If you run tests in parallel this lib helps to spin up dedicated mongodb servers for every test file in MacOS, *nix, Windows or CI environments (in most cases with zero-config).

typegoose/typegoose 971

Typegoose - Define Mongoose models using TypeScript classes.

hasezoey/yt-downloader-rust 2

youtube-dl wrapper in rust

hasezoey/OCJS_OS 1

An OS for OCJS

fabioformosa/typegoose-validation-error 0

This project reproduces a validation error that occurs using two classes with the same name

hasezoey/AwaitReactions-d.js 0

AwaitReactions fn

hasezoey/Cinnamon-Vivaldi-Modded 0

Its a Cinnamon Theme

hasezoey/DefinitelyTyped 0

The repository for high quality TypeScript type definitions.

hasezoey/git-webhook 0

Express module to intercept webhooks from Github, bitbucket, and other git webhooks systems.

hasezoey/github-todo 0

Github webhook to create issues for TODO items in commits.

issue commentnodkz/mongodb-memory-server

Test using mongodb-memory-server is failing/timing out

@hasezoey no worries, here is the code in the service where the doc is attempted to get created:

import { User } from "../models/User";
import mongoose from "mongoose"

export class UserService {
  static async createUser(userBody) {
    return User.create(userBody);
  }
}

Note that this code works when attached to a real remote mongo database (just not the in-memory db)

andylebo20

comment created time in 7 hours

issue commentnodkz/mongodb-memory-server

"MongoMemoryReplSet.waitUntilRunning" returning before all ready

Marking Issue as stale, will be closed in 7 days if no more activity is seen

mathieug

comment created time in 8 hours

issue openedtypegoose/typegoose

Field type loses array kind if get/set field options are defined

<!--

  • in versions, only include the Typegoose version you use (NPM or from GIT)
  • in "Code Example" add as many code blocks as needed, but when possible try to use an repo / gist
  • in "Do you know why it happenes replace the "no" if you know why
  • Make sure you read Mastering-Markdown -->

Versions

<!--Please confirm you are running the latest versions-->

<!--"0.0.0" means it is not used-->

  • NodeJS: 12.18.0
  • Typegoose(NPM): 7.4.2 <!--Please confirm that the verison is 7.0.x or above-->
  • mongoose: 5.10.18

What is the Problem?

Field type loses array kind if get/set field options are defined.

Code Example

  @prop({ type: Schema.Types.String, default: [] })
  public good?: string[] // will be string[]

  @prop({ type: Schema.Types.String, default: [], get: _.identity, set: _.identity })
  public bad: string[] // will be string

Do you know why it happens?

utils.initProperty returns array (correctly) but if options get/set are defined then the type is reset here: https://github.com/typegoose/typegoose/blob/39e5d0c2050b500bc3255438cf8fefa44c652b13/src/internal/processProp.ts#L182

created time in 14 hours

issue closedtypegoose/typegoose

How to create a conditional ttl index?

I want to create a conditional ttl to delete document after certain time under certian condition. How can I do that? With @index?

For example: if a user doesn't confirm his email in 15 seconds, then, his account will be deleted. How can I do that? I did the following code, but somehow, it doesn't work...

It looks like also the {createdAt: -1} reverse index doesn't work...

@modelOptions({ schemaOptions: { collection: "users", timestamps: true } })
@index(
  { createdAt: -1, confirmed: 1 },
  { expireAfterSeconds: 15, partialFilterExpression: { confirmed: false } }
)
class UserClass {
  @prop({ required: true, unique: true })
  public email!: string

  @prop({ default: false })
  public confirmed?: boolean

@prop({ default: Date.now, index: true })
  public createdAt?: Date
}

Versions

  • typegoose: 7.4.2
  • mongoose: 5.10.15 <!--Add more if needed-->

closed time in a day

blatoo

PR opened typegoose/typegoose

Update defaultClasses.md

I had a problem with ordering of decorators and hooks, this fixed it

image

just a docs update

+14 -1

0 comment

1 changed file

pr created time in a day

issue commenttypegoose/typegoose

Question about Array<string>

Marking Issue as stale, will be closed in 7 days if no more activity is seen

hmgibson23

comment created time in a day

issue commenttypegoose/typegoose

Cannot use same model on two connections.

I'm okay with the principle of having different names (my initial answer was a bit too quick), now my problem is if I try to set the customName through the optional options when calling getModelForClass it doesn't work. I've used the following test which exhibits the problem:

`it('if options.customName is defined to be used with automaticName through override', () => { @modelOptions({}) class CustomNameOverride { }

const model = getModelForClass(CustomNameOverride, { options: { customName: 'Suffix', automaticName: true } }); expect(model.modelName).toEqual('CustomNameOverride_Suffix');

const doc = new model(); const gotClass = getClassForDocument(doc); expect(gotClass).toEqual(CustomNameOverride); });`

I've got a potential fix too but can't push to the repository, let me know if you think the test case is valid I can send you a diff.

dcarniel

comment created time in 2 days

issue closedtypegoose/typegoose

Cast to ObjectId failed for value when creating document with reference

<!--

What to include in your Questions

  • Make sure you provide an understandable question
  • Make sure you provide all the needed code
  • Make sure you read Mastering-Markdown, thanks
  • If it is a small question, try to use our discord -->

I have two models, Account and Transaction:

// account.model.ts

export class Account extends defaultClasses.Base<string> {
    @prop()
    _id: string;

    @prop()
    name: string;
}

const AccountModel = getModelForClass(Account);

// transaction.model.ts

export class Transaction extends defaultClasses.Base<string> {
    @prop()
    _id: string;

    @prop()
    name: string;

    @prop({ ref: Account })
    account: Ref<Account>;
}

const TransactionModel = getModelForClass(Transaction);

Creating an account is fine, but when I want to create a transaction, I want to be able to pass in an account id as well:

TransactionModel({
            _id: "abc",
            name: "test",
            account: "acc1id",
        })

This doesn't work, and gives the following error:

Transaction validation failed: account: Cast to ObjectId failed for value "acc1id" at path "account" +3937ms
ValidationError: Transaction validation failed: account: Cast to ObjectId failed for value "acc1id" at path "account"
    at model.Document.invalidate (/srv/node_modules/mongoose/lib/document.js:2626:32)
    at model.$set (/srv/node_modules/mongoose/lib/document.js:1290:12)
    at model._handleIndex (/srv/node_modules/mongoose/lib/document.js:1019:14)
    at model.$set (/srv/node_modules/mongoose/lib/document.js:960:22)
    at model.Document (/srv/node_modules/mongoose/lib/document.js:150:12)
    at model.Model (/srv/node_modules/mongoose/lib/model.js:106:12)
    at new model (/srv/node_modules/mongoose/lib/model.js:4689:15)
    at /srv/node_modules/mongoose/lib/model.js:3055:22
    at /srv/node_modules/mongoose/lib/model.js:3091:7
    at Array.forEach (<anonymous>)
    at /srv/node_modules/mongoose/lib/model.js:3090:15
    at /srv/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:5
    at new Promise (<anonymous>)
    at promiseOrCallback (/srv/node_modules/mongoose/lib/helpers/promiseOrCallback.js:30:10)
    at Function.create (/srv/node_modules/mongoose/lib/model.js:3025:10)

I can create a transaction fine if I first fetch the account with the id and use that (account: fetchedAccount) but using a string doesn't work (account: fetchedAccount._id). Ideally I'd like to create a transaction without having to fetch the full account.

Versions

  • typegoose: 7.4.2
  • mongoose: 5.10.15 <!--Add more if needed-->

closed time in 2 days

j-waters

issue commenttypegoose/typegoose

Cast to ObjectId failed for value when creating document with reference

Ah that makes perfect sense thanks!

j-waters

comment created time in 2 days

issue commenttypegoose/typegoose

Cannot use same model on two connections.

You're right my first answer was a bit too quick, I looked again at the customName and it might work.

Though it looks like the getName function only looks at the options from the decorator and not the options merged from the getModelForClass: https://github.com/typegoose/typegoose/blob/51329a0ef6498075c71144fe94b35c2bd911695d/src/internal/utils.ts#L316

As a result getModelForClass doesn't see a change in the name and therefore keeps returning the same model.

Would it make sense to pass the merged options as an optional parameter to getName and use it it instead of what is gathered from the decorator if present ?

dcarniel

comment created time in 2 days

PR opened typegoose/typegoose

fixed typo in "which"

<!-- Try to use a template, found at .github/PULL_REQUEST_TEMPLATE/ here please don't forget to click on raw, and copy that, not the already "compiled" one -->

<!--

Make sure you have done these steps

  • Make sure you have Read & followed these steps in CONTRIBUTING
  • remove the parts that are not applicable
  • Please have "Allow edits from maintainers" activated -->

<!--Write your PR description here (above "Related Issues")--> fixed typo

Related Issues

<!--add "fixes" / "closes" before an number to indicate that these will be fixed by this pr-->

  • #1
+1 -1

0 comment

1 changed file

pr created time in 3 days

issue commenttypegoose/typegoose

Cannot use same model on two connections.

Thanks for the pointer but this unfortunately doesn't address my use case.

I want the same code to run on different connections (pointing to separate instances) depending on the request context (tenant). What I would need is simply the same model with a different database connection, the "caching mechanism prevents this because it ignores the "existingConnection" provided.

I'm not sure it would be an issue with the "getClass" methods since I'm always pointing to the same class, regardless of the underlying connection.

My understanding is that using Mongoose directly I could achieve what I want using the "conn.getModel(...)" method simply using different connections, that would get me twice the same model with different underlying connections. That cache mechanism seems to get in the way.

Happy to help and contribute if I can.

dcarniel

comment created time in 3 days

issue closedszokodiakos/typegoose

Cannot use same model on two connections.

In order to split database I'm trying to use the same model on multiple databases depending on context.

Unfortunately, when invoking the "getModelForClass" the internal cache used to build model only once ignores the connection (cf: https://github.com/szokodiakos/typegoose/blob/99f6be02dfb53c42fd5dd9209d4d73e4e2bcc97f/src/typegoose.ts#L51 ).

It would be interesting that this cache take the existingConnection (or existingMongoose) in account to allow instantiating multiple times the same model with a different underlying connection.

closed time in 3 days

dcarniel

issue commentszokodiakos/typegoose

Cannot use same model on two connections.

Sorry, I didn't check the actual repo. I copied my ticket there, thanks for your response.

dcarniel

comment created time in 3 days

issue openedtypegoose/typegoose

Cannot use same model on two connections.

In order to split database I'm trying to use the same model on multiple databases depending on context (running a service platform for multiple tenants, I'd like to keep data in separate mongoose instances for security and scalability).

Unfortunately, when invoking the "getModelForClass" the internal cache used to build model only once ignores the connection as illustrated here: https://github.com/typegoose/typegoose/blob/51329a0ef6498075c71144fe94b35c2bd911695d/src/typegoose.ts#L75

It would be interesting that this cache take the existingConnection (or existingMongoose) in account to allow instantiating multiple times the same model with a different underlying connection.

created time in 3 days

push eventtypegoose/typegoose

hasezoey

commit sha 9f18f7e61ba2c5b7c2731dbfc61563e0f73505c6

Deploying to gh-pages from @ 51329a0ef6498075c71144fe94b35c2bd911695d 🚀

view details

push time in 3 days

push eventtypegoose/typegoose

hasezoey

commit sha c39fd4ad619745b138babbac32f215c09317fadc

Deploying to gh-pages from @ f25b2fcc9f2dddab34cb85052ac6c388c993bd4a 🚀

view details

push time in 3 days

issue closedtypegoose/typegoose

Unable to get child class properties populated with discriminators

Overview

I have a class with a property array that seemed like a case for embedded discriminators. Try as I might the child class propertiess will not populate in the Mongo document.

I'm not really sure if I am doing something wrong or if Typegoose can't support what I am trying to do. Based upon the docs it seems that what I am trying to do should work. Any assistance or guidance would be most appreciated.

I've tried to include all of the relevant pieces to recreate. If there is something missing please let me know.

Typegoose model classes

class ResourceDbModel implements RestResource {
  public get id() {
    return this._id.toString();
  }
  public set id(val: string) {
    this._id = new mongoose.Types.ObjectId(val);
  }
  _id!: mongoose.Types.ObjectId;

  public get ver() {
    return this.__v;
  }
  public set ver(val: number) {
    this.__v = val;
  }
  __v!: number;
}

@modelOptions({
  options: { allowMixed: Severity.ALLOW },
  schemaOptions: {
  toJSON: {
    virtuals: true,
    transform: (_doc: any, ret: { _id: any; __v: any }, _opt: any) => {
      delete ret._id;
      delete ret.__v;
      return ret;
    }
  },
  toObject: {
    virtuals: true,
    transform: (_doc: any, ret: { _id: any; __v: any }, _opt: any) => {
      delete ret._id;
      delete ret.__v;
      return ret;
    }
  },
    collection: 'match-profiles'
  }
})
class MatchProfileDbModel extends ResourceDbModel
  implements MatchProfile {
  @prop({ required: true })
  name!: string;
  @prop()
  sportId!: SportIDs;
  @prop({
    type: mongoose.Schema.Types.Mixed
    // type: StatSchemaDbModel,
    // discriminators: () => [
    //   { type: ConditionalStatDbModel, value: StatType.CONDITIONAL },
    //   { type: DerivedStatDbModel, value: StatType.DERIVED },
    //   { type: DisplayStatDbModel, value: StatType.DISPLAY },
    //   { type: HornStatDbModel, value: StatType.HORN },
    //   { type: PeriodStatDbModel, value: StatType.PERIOD },
    //   { type: TimeOutStatDbModel, value: StatType.TIMEOUT },
    //   { type: TimerStatDbModel, value: StatType.TIMER }
    // ]
  })
  statSchemas!: StatSchema[];
  @prop({ type: mongoose.Schema.Types.Mixed })
  defaultConfigs!: ScoreboardOptions;  //Not relevant to this issue can be any for reproduction
  @prop({ required: true })
  trackPlayerStats!: boolean;
  @prop()
  defaultTeams?: {
    promptDefaultTeamNameConfirmation: boolean;
    teamNames: string[];
  };
}

class StatSchemaDbModel implements StatSchema {
  @prop()
  id!: string;
  @prop()
  label!: string;
  @prop()
  caption?: string;
  @prop()
  type!: StatType;
  @prop()
  valueType!: StatValueType;
  @prop()
  scope!: StatScope;
  @prop()
  disabledBy?: string[];
  @prop()
  initialValue?: number;
  @prop()
  subStats?: { title: string; values: { id: string; label: string }[] };
  @prop()
  attempts?: { track: boolean; label: string };
  @prop()
  trackByPeriod?: boolean;
  @prop()
  automation?: AutomationRule[];  //not relevant for example can be any
}

class PeriodStatDbModel extends StatSchemaDbModel
  implements PeriodStatSchema {
  @prop()
  numberPerMatch!: number;
  @prop()
  timeBetween?: number[];
  @prop()
  overtime?: {
    numberPer: number;
    duration?: number;
    timeBetween?: number;
    repeat: boolean;
  };
}

Statschema type definitions

interface StatSchema {
  id: string;
  label: string;
  caption?: string;
  type: StatType;   //string enum
  valueType: StatValueType; //string enum
  scope: StatScope; //string enum
  disabledBy?: string[]; 
  initialValue?: number;
  subStats?: {
    title: string;
    values: { id: string; label: string }[];
  };
  attempts?: {
    track: boolean;
    label: string;
  };
  trackByPeriod?: boolean;
  automation?: AutomationRule[];  //not relevant for example can be any
}

// For brevity only including one of the child classes

interface PeriodStatSchema extends StatSchema {
  numberPerMatch: number;
  timeBetween?: number[];
  overtime?: {
    numberPer: number;
    duration?: number; 
    timeBetween?: number; 
    repeat: boolean;
  };
}

Data Objects

const matchProfileSeeds: MatchProfile[] = [{
    id: '459ffd5835814e6b9474001a',
    ver: 0,
    name: 'Varsity Baseball',
    sportId: SportIDs.BASEBALL,
    statSchemas: BaseballStatSchema,
    defaultConfigs: {
      hornVolume: 100,
      hornTone: HornTone.BUZZER,
      brightness: 100,
      digitConfig: { leadingZeros: false, leftAlign: false },
      textConfig: {
        alignment: TextAlignment.CENTER,
        isInverted: false,
        fontName: 'FONT_8x48'
      }
    },
    trackPlayerStats: false,
    defaultTeams: {
      promptDefaultTeamNameConfirmation: true,
      teamNames: ['Home', 'Guest']
    }
  }
];

const BaseballStatSchema: StatSchema[] = [
  {
    id: BaseballStatIDs.POINTS,
    label: 'Runs',
    type: StatType.BASIC,
    valueType: StatValueType.NUMBER,
    scope: StatScope.TEAM_ONLY,
    trackByPeriod: true
  },
  {
    id: BaseballStatIDs.INNING,
    label: 'Inning',
    type: StatType.PERIOD,
    valueType: StatValueType.NUMBER,
    scope: StatScope.MATCH,
    numberPerMatch: 9,
    overtime: {
      numberPer: 1,
      duration: 0,
      repeat: true
    }
  } as PeriodStatSchema ];

We seed our db collections using static objects (i.e. matchProfileSeeds) with a model.create() passing in the object array.

Code snippet of collection population

const matchProfileModel = getModelForClass(MatchProfileDbModel);
//...
matchProfileModel.create(matchProfileSeeds)

If I use StatSchemaDbModel as the type for statSchemas in MatchProfileDbModel I cannot get the statSchemas subdocs to populate the values from the child (discriminator) classes. The only way that they will populate is to make the type Schema.Types.Mixed which is how it was originally implemented in the mongoose schema.

I've tried various flavors of trying to push the appropriate statSchema child class type onto the statSchemas array within the MatchProfileDbModel object without any luck. The child class specific properties, which in this case would be overtime and numberPerMatch are never saved to the document in the db.

My futile various attempts at adding the discriminated class objects

const statSchemaModel = getDiscriminatorModelForClass(
  this.matchProfileModel,
  StatSchemaDbModel
);

// const matchProfilesToSave: MatchProfile[] = [];
matchProfileSeeds.map(async matchProfile => {
  // const profileToSave = cloneDeep(matchProfile);
  const profileToSave: MatchProfileDbModel = this.matchProfileModel.hydrate(
    { _id: matchProfile.id, ...matchProfile }
  );
  profileToSave.statSchemas = [];
  matchProfile.statSchemas.map(schema => {
    switch (schema.type) {
      case StatType.PERIOD:  //'period'
        // const statSchema = schema
        const statSchema = statSchemaModel.hydrate(schema);
        profileToSave.statSchemas.push(statSchema);
        // profileToSave.statSchemas.push(statSchema as PeriodStatDbModel);
        break;
      default:
        break;
    }
  });
  // matchProfilesToSave.push(profileToSave);
  // await new this.matchProfileModel(profileToSave).save();
  await this.matchProfileModel.update(
    { _id: profileToSave.id },
    profileToSave,
    { upsert: true }
  );
});

Versions

  • typegoose: 7.4.1
  • mongoose: 5.10.7 <!--Add more if needed-->

closed time in 3 days

sdunnin

issue commenttypegoose/typegoose

Unable to get child class properties populated with discriminators

Closing Issue because it is marked as stale

sdunnin

comment created time in 3 days

issue openedszokodiakos/typegoose

Cannot use same model on two connections.

In order to split database I'm trying to use the same model on multiple databases depending on context.

Unfortunately, when invoking the "getModelForClass" the internal cache used to build model only once ignores the connection (cf: https://github.com/szokodiakos/typegoose/blob/99f6be02dfb53c42fd5dd9209d4d73e4e2bcc97f/src/typegoose.ts#L51 ).

It would be interesting that this cache take the existingConnection (or existingMongoose) in account to allow instantiating multiple times the same model with a different underlying connection.

created time in 3 days

pull request commenttypegoose/typegoose

Update hooks.md

image

done, so it's like a top of page header now.

dcsan

comment created time in 4 days

issue openedtypegoose/typegoose

Cast to ObjectId failed for value when creating document with reference

<!--

What to include in your Questions

  • Make sure you provide an understandable question
  • Make sure you provide all the needed code
  • Make sure you read Mastering-Markdown, thanks
  • If it is a small question, try to use our discord -->

I have two models, Account and Transaction:

// account.model.ts

export class Account extends defaultClasses.Base<string> {
    @prop()
    _id: string;

    @prop()
    name: string;
}

const AccountModel = getModelForClass(Account);

// transaction.model.ts

export class Transaction extends defaultClasses.Base<string> {
    @prop()
    _id: string;

    @prop()
    name: string;

    @prop({ ref: Account })
    account: Ref<Account>;
}

const TransactionModel = getModelForClass(Transaction);

Creating an account is fine, but when I want to create a transaction, I want to be able to pass in an account id as well:

TransactionModel({
            _id: "abc",
            name: "test",
            account: "acc1id",
        })

This doesn't work, and gives the following error:

Transaction validation failed: account: Cast to ObjectId failed for value "acc1id" at path "account" +3937ms
ValidationError: Transaction validation failed: account: Cast to ObjectId failed for value "acc1id" at path "account"
    at model.Document.invalidate (/srv/node_modules/mongoose/lib/document.js:2626:32)
    at model.$set (/srv/node_modules/mongoose/lib/document.js:1290:12)
    at model._handleIndex (/srv/node_modules/mongoose/lib/document.js:1019:14)
    at model.$set (/srv/node_modules/mongoose/lib/document.js:960:22)
    at model.Document (/srv/node_modules/mongoose/lib/document.js:150:12)
    at model.Model (/srv/node_modules/mongoose/lib/model.js:106:12)
    at new model (/srv/node_modules/mongoose/lib/model.js:4689:15)
    at /srv/node_modules/mongoose/lib/model.js:3055:22
    at /srv/node_modules/mongoose/lib/model.js:3091:7
    at Array.forEach (<anonymous>)
    at /srv/node_modules/mongoose/lib/model.js:3090:15
    at /srv/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:5
    at new Promise (<anonymous>)
    at promiseOrCallback (/srv/node_modules/mongoose/lib/helpers/promiseOrCallback.js:30:10)
    at Function.create (/srv/node_modules/mongoose/lib/model.js:3025:10)

I can create a transaction fine if I first fetch the account with the id and use that (account: fetchedAccount) but using a string doesn't work (account: fetchedAccount._id). Ideally I'd like to create a transaction without having to fetch the full account.

Versions

  • typegoose: 7.4.2
  • mongoose: 5.10.15 <!--Add more if needed-->

created time in 4 days

PR opened typegoose/typegoose

Fix incorrect documentation URL
  • fixes incorrect URL to model options documentation
+1 -1

0 comment

1 changed file

pr created time in 5 days

issue openednodkz/mongodb-memory-server

Test using mongodb-memory-server is failing/timing out

I’m setting up mongodb-memory-server in my backend for test purposes and am experiencing some issues when running tests that I am hoping someone could help me debug. My issue is that when I run my test (which will create a mongodb doc somewhere in the service being tested), the test times out. As I understand it, this is because when the test is executed and a new mongo doc is trying to be created during the test, I console log mongoose.connection.readyState and it says it’s 0, meaning that mongoose is disconnected. This is strange to me because I added console logs to my connectMongoose() function (pictured below) and it says that mongoose is connected. So my main question is why does it say mongoose is connected at the end of connectMongoose(), but it says it’s disconnected during the execution of the unit test/service function? How can I ensure that MongoDB-memory-server is fully connected prior to test execution?

Below is a screenshot showing how I am doing the mongoose test connection. Screen Shot 2020-11-26 at 3 10 26 PM

Below this is a screenshot of exactly where and how mongodb-memory-server is being used Screen Shot 2020-11-26 at 3 11 09 PM

Here is a screenshot of my jest.config.js: Screen Shot 2020-11-26 at 3 11 32 PM

And finally the actual test file which has the failing test (what I’m asking about): Screen Shot 2020-11-26 at 3 11 51 PM

Please let me know if anyone needs any further clarification or screenshots, etc. Thank you so much in advance for your help!

created time in 5 days

issue commenttypegoose/typegoose

Virtual id setter called twice during model create

Marking Issue as stale, will be closed in 7 days if no more activity is seen

sdunnin

comment created time in 5 days

issue commenttypegoose/typegoose

How to create a conditional ttl index?

Hi all,

Sorry, I think, it was my mistake, I didn't wait for enough time. I saw it works now. Sorry for the inconvenient.

Another question: does the index: true over the public createAt?: Date necessary ? Shall I also set confirmed as index?

blatoo

comment created time in 5 days

issue closedtypegoose/typegoose

using pre hook causes ts error

DOH! I forgot to import. I'll make a change to the docs.

Versions

"@typegoose/typegoose": "^7.4.2", "mongoose": "^5.10.15", "typescript": "^4.1.2"

Version 4.1.2

What is the Problem?

get an error on trying to use hooks:

  src/models/Riddle.ts:21:22
    21 @pre<Riddle>('save', function () {
                            ~~~~~~~~
    An outer value of 'this' is shadowed by this container.

Code Example

https://typegoose.github.io/typegoose/docs/api/decorators/hooks

Do you know why it happens?

tsconfig has these flags:

    "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
    "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */

no

➜  server git:(tadmin) ✗ yarn ts-info
yarn run v1.17.3
$ tsc --version
Version 4.0.5
✨  Done in 0.32s.
➜  server git:(tadmin) ✗ yarn tsc
yarn run v1.17.3
$ tsc
src/models/Riddle.ts:21:2 - error TS2304: Cannot find name 'pre'.

21 @pre<Riddle>('save', function () {
    ~~~


Found 1 error.

error Command failed with exit code 2.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
➜  server git:(tadmin) ✗

closed time in 6 days

dcsan

PR opened typegoose/typegoose

Update hooks.md

Tiny minor change to docs remind people to import the pre, post hooks. I made the mistake, maybe someone else will too. I thought the 'pre' decorator was a language feature, not a specific decorator to import.

image

https://github.com/typegoose/typegoose/issues/415

<!-- Try to use a template, found at .github/PULL_REQUEST_TEMPLATE/ here please don't forget to click on raw, and copy that, not the already "compiled" one -->

<!--

Make sure you have done these steps

  • Make sure you have Read & followed these steps in CONTRIBUTING
  • remove the parts that are not applicable
  • Please have "Allow edits from maintainers" activated -->

<!--Write your PR description here (above "Related Issues")-->

Related Issues

<!--add "fixes" / "closes" before an number to indicate that these will be fixed by this pr-->

  • #1
+7 -0

0 comment

1 changed file

pr created time in 6 days

issue openedtypegoose/typegoose

using pre hook causes ts error

DOH! I forgot to import. I'll make a change to the docs.

Versions

"@typegoose/typegoose": "^7.4.2", "mongoose": "^5.10.15", "typescript": "^4.1.2"

Version 4.1.2

What is the Problem?

get an error on trying to use hooks:

  src/models/Riddle.ts:21:22
    21 @pre<Riddle>('save', function () {
                            ~~~~~~~~
    An outer value of 'this' is shadowed by this container.

Code Example

https://typegoose.github.io/typegoose/docs/api/decorators/hooks

Do you know why it happens?

tsconfig has these flags:

    "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
    "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */

no

➜  server git:(tadmin) ✗ yarn ts-info
yarn run v1.17.3
$ tsc --version
Version 4.0.5
✨  Done in 0.32s.
➜  server git:(tadmin) ✗ yarn tsc
yarn run v1.17.3
$ tsc
src/models/Riddle.ts:21:2 - error TS2304: Cannot find name 'pre'.

21 @pre<Riddle>('save', function () {
    ~~~


Found 1 error.

error Command failed with exit code 2.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
➜  server git:(tadmin) ✗

created time in 6 days

issue openedtypegoose/typegoose

How to create a conditional ttl index?

I want to create a conditional ttl to delete document after certain time under certian condition.

For example: if a user doesn't confirm his email in 15 seconds, then, his account will be deleted. How can I do that? I did the following code, but somehow, it doesn't work...

@modelOptions({ schemaOptions: { collection: "users", timestamps: true } })
@index(
  { createdAt: -1, confirmed: 1 },
  { expireAfterSeconds: 15, partialFilterExpression: { confirmed: false } }
)
class UserClass {
  @prop({ required: true, unique: true })
  public email!: string

  @prop({ default: false })
  public confirmed?: boolean

@prop({ default: Date.now, index: true })
  public createdAt?: Date
}

Versions

  • typegoose: 7.4.2
  • mongoose: 5.10.15 <!--Add more if needed-->

created time in 6 days

more