[
  {
    "path": ".circleci/config.yml",
    "content": "version: 2\n\naliases:\n  - &restore-cache\n    restore_cache:\n      key: dependency-cache-{{ checksum \"package.json\" }}\n  - &install-deps\n    run:\n      name: Install dependencies\n      command: npm install --ignore-scripts\n  - &build-packages\n    run:\n      name: Build\n      command: npm run build\n\njobs:\n  build:\n    working_directory: ~/nest\n    docker:\n      - image: cimg/node:24.13.0\n    steps:\n      - checkout\n      - restore_cache:\n          key: dependency-cache-{{ checksum \"package.json\" }}\n      - run:\n          name: Install dependencies\n          command: npm install --ignore-scripts\n      - save_cache:\n          key: dependency-cache-{{ checksum \"package.json\" }}\n          paths:\n            - ./node_modules\n      - run:\n          name: Build\n          command: npm run build\n  integration_tests:\n    working_directory: ~/nest\n    machine: true\n    steps:\n      - checkout\n      - run:\n          name: Prepare nvm\n          command: |\n            echo 'export NVM_DIR=\"/opt/circleci/.nvm\"' >> $BASH_ENV\n            echo ' [ -s \"$NVM_DIR/nvm.sh\" ] && \\. \"$NVM_DIR/nvm.sh\"' >> $BASH_ENV\n      - run:\n          name: Upgrade Node.js\n          command: |\n            nvm install v20\n            node -v\n            nvm alias default v20\n      - run:\n          name: Install Docker Compose\n          command: |\n            curl -L https://github.com/docker/compose/releases/download/1.19.0/docker-compose-`uname -s`-`uname -m` > ~/docker-compose\n            chmod +x ~/docker-compose\n            sudo mv ~/docker-compose /usr/local/bin/docker-compose\n      - *install-deps\n      - run:\n          name: Prepare\n          command: |\n            docker-compose up -d\n            sleep 10\n      - run:\n          name: List containers\n          command: docker ps\n      - run:\n          name: e2e tests\n          command: npm run test:e2e\n\nworkflows:\n  version: 2\n  build-and-test:\n    jobs:\n      - build\n      - integration_tests:\n          requires:\n            - build\n"
  },
  {
    "path": ".commitlintrc.json",
    "content": "{\n  \"extends\": [\"@commitlint/config-angular\"],\n  \"rules\": {\n    \"subject-case\": [\n      2,\n      \"always\",\n      [\"sentence-case\", \"start-case\", \"pascal-case\", \"upper-case\", \"lower-case\"]\n    ],\n    \"type-enum\": [\n      2,\n      \"always\",\n      [\n        \"build\",\n        \"chore\",\n        \"ci\",\n        \"docs\",\n        \"feat\",\n        \"fix\",\n        \"perf\",\n        \"refactor\",\n        \"revert\",\n        \"style\",\n        \"test\",\n        \"sample\"\n      ]\n    ]\n  }\n}\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/Bug_report.yml",
    "content": "name: \"\\U0001F41B Bug Report\"\ndescription: \"If something isn't working as expected \\U0001F914\"\nlabels: [\"needs triage\", \"bug\"]\nbody:\n  - type: markdown\n    attributes:\n      value: |\n        ## :warning: We use GitHub Issues to track bug reports, feature requests and regressions\n \n        If you are not sure that your issue is a bug, you could:\n\n        - use our [Discord community](https://discord.gg/NestJS)\n        - use [StackOverflow using the tag `nestjs`](https://stackoverflow.com/questions/tagged/nestjs)\n        - If it's just a quick question you can ping [our Twitter](https://twitter.com/nestframework)\n\n        **NOTE:** You don't need to answer questions that you know that aren't relevant.\n\n        ---\n\n  - type: checkboxes\n    attributes:\n      label: \"Is there an existing issue for this?\"\n      description: \"Please search [here](./?q=is%3Aissue) to see if an issue already exists for the bug you encountered\"\n      options:\n      - label: \"I have searched the existing issues\"\n        required: true\n\n  - type: textarea\n    validations:\n      required: true\n    attributes:\n      label: \"Current behavior\"\n      description: \"How the issue manifests?\"\n\n  - type: input\n    validations:\n      required: true\n    attributes:\n      label: \"Minimum reproduction code\"\n      description: \"An URL to some git repository or gist that reproduces this issue. [Wtf is a minimum reproduction?](https://jmcdo29.github.io/wtf-is-a-minimum-reproduction)\"\n      placeholder: \"https://github.com/...\"\n\n  - type: textarea\n    attributes:\n      label: \"Steps to reproduce\"\n      description: |\n        How the issue manifests?\n        You could leave this blank if you alread write this in your reproduction code/repo\n      placeholder: |\n        1. `npm i`\n        2. `npm start:dev`\n        3. See error...\n\n  - type: textarea\n    validations:\n      required: true\n    attributes:\n      label: \"Expected behavior\"\n      description: \"A clear and concise description of what you expected to happend (or code)\"\n\n  - type: markdown\n    attributes:\n      value: |\n        ---\n\n  - type: input\n    validations:\n      required: true\n    attributes:\n      label: \"Package version\"\n      description: |\n        Which version of `@nestjs/mongoose` are you using?\n        **Tip**: Make sure that all of yours `@nestjs/*` dependencies are in sync!\n      placeholder: \"8.1.3\"\n\n  - type: input\n    attributes:\n      label: \"mongoose version\"\n      description: \"Which version of `mongoose` are you using?\"\n      placeholder: \"6.0.9\"\n\n  - type: input\n    attributes:\n      label: \"NestJS version\"\n      description: \"Which version of `@nestjs/core` are you using?\"\n      placeholder: \"8.1.3\"\n\n  - type: input\n    attributes:\n      label: \"Node.js version\"\n      description: \"Which version of Node.js are you using?\"\n      placeholder: \"14.17.6\"\n\n  - type: checkboxes\n    attributes:\n      label: \"In which operating systems have you tested?\"\n      options:\n        - label: macOS\n        - label: Windows\n        - label: Linux\n\n  - type: markdown\n    attributes:\n      value: |\n        ---\n\n  - type: textarea\n    attributes:\n      label: \"Other\"\n      description: |\n        Anything else relevant? eg: Logs, OS version, IDE, package manager, etc.\n        **Tip:** You can attach images, recordings or log files by clicking this area to highlight it and then dragging files in\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/Feature_request.yml",
    "content": "name: \"\\U0001F680 Feature Request\"\ndescription: \"I have a suggestion \\U0001F63B!\"\nlabels: [\"feature\"]\nbody:\n  - type: markdown\n    attributes:\n      value: |\n        ## :warning: We use GitHub Issues to track bug reports, feature requests and regressions\n \n        If you are not sure that your issue is a bug, you could:\n\n        - use our [Discord community](https://discord.gg/NestJS)\n        - use [StackOverflow using the tag `nestjs`](https://stackoverflow.com/questions/tagged/nestjs)\n        - If it's just a quick question you can ping [our Twitter](https://twitter.com/nestframework)\n\n        ---\n\n  - type: checkboxes\n    attributes:\n      label: \"Is there an existing issue that is already proposing this?\"\n      description: \"Please search [here](./?q=is%3Aissue) to see if an issue already exists for the feature you are requesting\"\n      options:\n      - label: \"I have searched the existing issues\"\n        required: true\n\n  - type: textarea\n    validations:\n      required: true\n    attributes:\n      label: \"Is your feature request related to a problem? Please describe it\"\n      description: \"A clear and concise description of what the problem is\"\n      placeholder: |\n        I have an issue when ...\n\n  - type: textarea\n    validations:\n      required: true\n    attributes:\n      label: \"Describe the solution you'd like\"\n      description: \"A clear and concise description of what you want to happen. Add any considered drawbacks\"\n\n  - type: textarea\n    attributes:\n      label: \"Teachability, documentation, adoption, migration strategy\"\n      description: \"If you can, explain how users will be able to use this and possibly write out a version the docs. Maybe a screenshot or design?\"\n\n  - type: textarea\n    validations:\n      required: true\n    attributes:\n      label: \"What is the motivation / use case for changing the behavior?\"\n      description: \"Describe the motivation or the concrete use case\"\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/Regression.yml",
    "content": "name: \"\\U0001F4A5 Regression\"\ndescription: \"Report an unexpected behavior while upgrading your Nest application!\"\nlabels: [\"needs triage\"]\nbody:\n  - type: markdown\n    attributes:\n      value: |\n        ## :warning: We use GitHub Issues to track bug reports, feature requests and regressions\n \n        If you are not sure that your issue is a bug, you could:\n\n        - use our [Discord community](https://discord.gg/NestJS)\n        - use [StackOverflow using the tag `nestjs`](https://stackoverflow.com/questions/tagged/nestjs)\n        - If it's just a quick question you can ping [our Twitter](https://twitter.com/nestframework)\n\n        **NOTE:** You don't need to answer questions that you know that aren't relevant.\n\n        ---\n\n  - type: checkboxes\n    attributes:\n      label: \"Did you read the migration guide?\"\n      description: \"Check out the [migration guide here](https://docs.nestjs.com/migration-guide)!\"\n      options:\n      - label: \"I have read the whole migration guide\"\n        required: false\n\n  - type: checkboxes\n    attributes:\n      label: \"Is there an existing issue that is already proposing this?\"\n      description: \"Please search [here](./?q=is%3Aissue) to see if an issue already exists for the feature you are requesting\"\n      options:\n      - label: \"I have searched the existing issues\"\n        required: true\n\n  - type: input\n    attributes:\n      label: \"Potential Commit/PR that introduced the regression\"\n      description: \"If you have time to investigate, what PR/date/version introduced this issue\"\n      placeholder: \"PR #123 or commit 5b3c4a4\"\n\n  - type: input\n    attributes:\n      label: \"Versions\"\n      description: \"From which version of `@nestjs/mongoose` to which version you are upgrading\"\n      placeholder: \"8.1.0 -> 8.1.3\"\n\n  - type: textarea\n    validations:\n      required: true\n    attributes:\n      label: \"Describe the regression\"\n      description: \"A clear and concise description of what the regression is\"\n\n  - type: textarea\n    attributes:\n      label: \"Minimum reproduction code\"\n      description: |\n        Please share a git repo, a gist, or step-by-step instructions. [Wtf is a minimum reproduction?](https://jmcdo29.github.io/wtf-is-a-minimum-reproduction)\n        **Tip:** If you leave a minimum repository, we will understand your issue faster!\n      value: |\n        ```ts\n\n        ```\n\n  - type: textarea\n    validations:\n      required: true\n    attributes:\n      label: \"Expected behavior\"\n      description: \"A clear and concise description of what you expected to happend (or code)\"\n\n  - type: textarea\n    attributes:\n      label: \"Other\"\n      description: |\n        Anything else relevant? eg: Logs, OS version, IDE, package manager, etc.\n        **Tip:** You can attach images, recordings or log files by clicking this area to highlight it and then dragging files in\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/config.yml",
    "content": "## To encourage contributors to use issue templates, we don't allow blank issues\nblank_issues_enabled: false\n\ncontact_links:\n  - name: \"\\u2753 Discord Community of NestJS\"\n    url: \"https://discord.gg/NestJS\"\n    about: \"Please ask support questions or discuss suggestions/enhancements here.\"\n"
  },
  {
    "path": ".github/PULL_REQUEST_TEMPLATE.md",
    "content": "## PR Checklist\nPlease check if your PR fulfills the following requirements:\n\n- [ ] The commit message follows our guidelines: https://github.com/nestjs/nest/blob/master/CONTRIBUTING.md\n- [ ] Tests for the changes have been added (for bug fixes / features)\n- [ ] Docs have been added / updated (for bug fixes / features)\n\n\n## PR Type\nWhat kind of change does this PR introduce?\n\n<!-- Please check the one that applies to this PR using \"x\". -->\n- [ ] Bugfix\n- [ ] Feature\n- [ ] Code style update (formatting, local variables)\n- [ ] Refactoring (no functional changes, no api changes)\n- [ ] Build related changes\n- [ ] CI related changes\n- [ ] Other... Please describe:\n\n## What is the current behavior?\n<!-- Please describe the current behavior that you are modifying, or link to a relevant issue. -->\n\nIssue Number: N/A\n\n\n## What is the new behavior?\n\n\n## Does this PR introduce a breaking change?\n- [ ] Yes\n- [ ] No\n\n<!-- If this PR contains a breaking change, please describe the impact and migration path for existing applications below. -->\n\n\n## Other information\n"
  },
  {
    "path": ".gitignore",
    "content": "# dependencies\n/node_modules\n\n# IDE\n/.idea\n/.awcache\n/.vscode\n\n# misc\nnpm-debug.log\n.DS_Store\n\n# tests\n/test\n/coverage\n/.nyc_output\n\n# dist\ndist\n"
  },
  {
    "path": ".husky/.gitignore",
    "content": "_"
  },
  {
    "path": ".husky/commit-msg",
    "content": "npx --no-install commitlint --edit $1\n"
  },
  {
    "path": ".husky/pre-commit",
    "content": "npx --no-install lint-staged\n"
  },
  {
    "path": ".npmignore",
    "content": "# source\nlib\nindex.ts\n\n# tests\n/tests\n\n# misc\npackage-lock.json\n.eslintrc.js\ntsconfig.json\ntsconfig.build.json\n.prettierrc\n.prettierrc\n.commitlintrc.json\ndocker-compose.yml\n.husky/\n.github/\n.circleci/\nrenovate.json"
  },
  {
    "path": ".prettierrc",
    "content": "{\n  \"trailingComma\": \"all\",\n  \"singleQuote\": true\n}"
  },
  {
    "path": ".release-it.json",
    "content": "{\n  \"git\": {\n    \"commitMessage\": \"chore(): release v${version}\"\n  },\n  \"github\": {\n    \"release\": true\n  }\n}\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contributing to Nest\n\nWe would love for you to contribute to Nest and help make it even better than it is\ntoday! As a contributor, here are the guidelines we would like you to follow:\n\n - [Code of Conduct](#coc)\n - [Question or Problem?](#question)\n - [Issues and Bugs](#issue)\n - [Feature Requests](#feature)\n - [Submission Guidelines](#submit)\n - [Coding Rules](#rules)\n - [Commit Message Guidelines](#commit)\n <!-- - [Signing the CLA](#cla) -->\n\n<!-- ## <a name=\"coc\"></a> Code of Conduct\nHelp us keep Nest open and inclusive. Please read and follow our [Code of Conduct][coc]. -->\n\n## <a name=\"question\"></a> Got a Question or Problem?\n\n**Do not open issues for general support questions as we want to keep GitHub issues for bug reports and feature requests.** You've got much better chances of getting your question answered on [Stack Overflow](https://stackoverflow.com/questions/tagged/nestjs) where the questions should be tagged with tag `nestjs`.\n\nStack Overflow is a much better place to ask questions since:\n\n<!-- - there are thousands of people willing to help on Stack Overflow [maybe one day] -->\n- questions and answers stay available for public viewing so your question / answer might help someone else\n- Stack Overflow's voting system assures that the best answers are prominently visible.\n\nTo save your and our time, we will systematically close all issues that are requests for general support and redirect people to Stack Overflow.\n\nIf you would like to chat about the question in real-time, you can reach out via [our discord channel][discord].\n\n## <a name=\"issue\"></a> Found a Bug?\nIf you find a bug in the source code, you can help us by\n[submitting an issue](#submit-issue) to our [GitHub Repository][github]. Even better, you can\n[submit a Pull Request](#submit-pr) with a fix.\n\n## <a name=\"feature\"></a> Missing a Feature?\nYou can *request* a new feature by [submitting an issue](#submit-issue) to our GitHub\nRepository. If you would like to *implement* a new feature, please submit an issue with\na proposal for your work first, to be sure that we can use it.\nPlease consider what kind of change it is:\n\n* For a **Major Feature**, first open an issue and outline your proposal so that it can be\ndiscussed. This will also allow us to better coordinate our efforts, prevent duplication of work,\nand help you to craft the change so that it is successfully accepted into the project. For your issue name, please prefix your proposal with `[discussion]`, for example \"[discussion]: your feature idea\".\n* **Small Features** can be crafted and directly [submitted as a Pull Request](#submit-pr).\n\n## <a name=\"submit\"></a> Submission Guidelines\n\n### <a name=\"submit-issue\"></a> Submitting an Issue\n\nBefore you submit an issue, please search the issue tracker, maybe an issue for your problem already exists and the discussion might inform you of workarounds readily available.\n\nWe want to fix all the issues as soon as possible, but before fixing a bug we need to reproduce and confirm it. In order to reproduce bugs we will systematically ask you to provide a minimal reproduction scenario using a repository or [Gist](https://gist.github.com/). Having a live, reproducible scenario gives us wealth of important information without going back & forth to you with additional questions like:\n\n- version of NestJS used\n- 3rd-party libraries and their versions\n- and most importantly - a use-case that fails\n\n<!--\n// TODO we need to create a playground, similar to plunkr\n\nA minimal reproduce scenario using a repository or Gist allows us to quickly confirm a bug (or point out coding problem) as well as confirm that we are fixing the right problem. If neither of these are not a suitable way to demonstrate the problem (for example for issues related to our npm packaging), please create a standalone git repository demonstrating the problem. -->\n\n<!-- We will be insisting on a minimal reproduce scenario in order to save maintainers time and ultimately be able to fix more bugs. Interestingly, from our experience users often find coding problems themselves while preparing a minimal plunk. We understand that sometimes it might be hard to extract essentials bits of code from a larger code-base but we really need to isolate the problem before we can fix it. -->\n\nUnfortunately, we are not able to investigate / fix bugs without a minimal reproduction, so if we don't hear back from you we are going to close an issue that don't have enough info to be reproduced.\n\nYou can file new issues by filling out our [new issue form](https://github.com/nestjs/nest/issues/new).\n\n\n### <a name=\"submit-pr\"></a> Submitting a Pull Request (PR)\nBefore you submit your Pull Request (PR) consider the following guidelines:\n\n1. Search [GitHub](https://github.com/nestjs/nest/pulls) for an open or closed PR\n  that relates to your submission. You don't want to duplicate effort.\n<!-- 1. Please sign our [Contributor License Agreement (CLA)](#cla) before sending PRs.\n  We cannot accept code without this. -->\n1. Fork the nestjs/nest repo.\n1. Make your changes in a new git branch:\n\n     ```shell\n     git checkout -b my-fix-branch master\n     ```\n\n1. Create your patch, **including appropriate test cases**.\n1. Follow our [Coding Rules](#rules).\n1. Run the full Nest test suite, as described in the [developer documentation][dev-doc],\n  and ensure that all tests pass.\n1. Commit your changes using a descriptive commit message that follows our\n  [commit message conventions](#commit). Adherence to these conventions\n  is necessary because release notes are automatically generated from these messages.\n\n     ```shell\n     git commit -a\n     ```\n    Note: the optional commit `-a` command line option will automatically \"add\" and \"rm\" edited files.\n\n1. Push your branch to GitHub:\n\n    ```shell\n    git push origin my-fix-branch\n    ```\n\n1. In GitHub, send a pull request to `nestjs:master`.\n* If we suggest changes then:\n  * Make the required updates.\n  * Re-run the Nest test suites to ensure tests are still passing.\n  * Rebase your branch and force push to your GitHub repository (this will update your Pull Request):\n\n    ```shell\n    git rebase master -i\n    git push -f\n    ```\n\nThat's it! Thank you for your contribution!\n\n#### After your pull request is merged\n\nAfter your pull request is merged, you can safely delete your branch and pull the changes\nfrom the main (upstream) repository:\n\n* Delete the remote branch on GitHub either through the GitHub web UI or your local shell as follows:\n\n    ```shell\n    git push origin --delete my-fix-branch\n    ```\n\n* Check out the master branch:\n\n    ```shell\n    git checkout master -f\n    ```\n\n* Delete the local branch:\n\n    ```shell\n    git branch -D my-fix-branch\n    ```\n\n* Update your master with the latest upstream version:\n\n    ```shell\n    git pull --ff upstream master\n    ```\n\n## <a name=\"rules\"></a> Coding Rules\nTo ensure consistency throughout the source code, keep these rules in mind as you are working:\n\n* All features or bug fixes **must be tested** by one or more specs (unit-tests).\n<!--\n// We're working on auto-documentation.\n* All public API methods **must be documented**. (Details TBC). -->\n* We follow [Google's JavaScript Style Guide][js-style-guide], but wrap all code at\n  **100 characters**. An automated formatter is available, see\n  [DEVELOPER.md](docs/DEVELOPER.md#clang-format).\n\n## <a name=\"commit\"></a> Commit Message Guidelines\n\nWe have very precise rules over how our git commit messages can be formatted.  This leads to **more\nreadable messages** that are easy to follow when looking through the **project history**.  But also,\nwe use the git commit messages to **generate the Nest change log**.\n\n### Commit Message Format\nEach commit message consists of a **header**, a **body** and a **footer**.  The header has a special\nformat that includes a **type**, a **scope** and a **subject**:\n\n```\n<type>(<scope>): <subject>\n<BLANK LINE>\n<body>\n<BLANK LINE>\n<footer>\n```\n\nThe **header** is mandatory and the **scope** of the header is optional.\n\nAny line of the commit message cannot be longer 100 characters! This allows the message to be easier\nto read on GitHub as well as in various git tools.\n\nFooter should contain a [closing reference to an issue](https://help.github.com/articles/closing-issues-via-commit-messages/) if any.\n\nSamples: (even more [samples](https://github.com/nestjs/nest/commits/master))\n\n```\ndocs(changelog) update change log to beta.5\n```\n```\nfix(@nestjs/core) need to depend on latest rxjs and zone.js\n\nThe version in our package.json gets copied to the one we publish, and users need the latest of these.\n```\n\n### Revert\nIf the commit reverts a previous commit, it should begin with `revert: `, followed by the header of the reverted commit. In the body it should say: `This reverts commit <hash>.`, where the hash is the SHA of the commit being reverted.\n\n### Type\nMust be one of the following:\n\n* **build**: Changes that affect the build system or external dependencies (example scopes: gulp, broccoli, npm)\n* **chore**: Updating tasks etc; no production code change\n* **ci**: Changes to our CI configuration files and scripts (example scopes: Travis, Circle, BrowserStack, SauceLabs)\n* **docs**: Documentation only changes\n* **feat**: A new feature\n* **fix**: A bug fix\n* **perf**: A code change that improves performance\n* **refactor**: A code change that neither fixes a bug nor adds a feature\n* **style**: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)\n* **test**: Adding missing tests or correcting existing tests\n\n\n### Subject\nThe subject contains succinct description of the change:\n\n* use the imperative, present tense: \"change\" not \"changed\" nor \"changes\"\n* don't capitalize first letter\n* no dot (.) at the end\n\n### Body\nJust as in the **subject**, use the imperative, present tense: \"change\" not \"changed\" nor \"changes\".\nThe body should include the motivation for the change and contrast this with previous behavior.\n\n### Footer\nThe footer should contain any information about **Breaking Changes** and is also the place to\nreference GitHub issues that this commit **Closes**.\n\n**Breaking Changes** should start with the word `BREAKING CHANGE:` with a space or two newlines. The rest of the commit message is then used for this.\n\nA detailed explanation can be found in this [document][commit-message-format].\n\n<!-- ## <a name=\"cla\"></a> Signing the CLA\n\nPlease sign our Contributor License Agreement (CLA) before sending pull requests. For any code\nchanges to be accepted, the CLA must be signed. It's a quick process, we promise!\n\n* For individuals we have a [simple click-through form][individual-cla].\n* For corporations we'll need you to\n  [print, sign and one of scan+email, fax or mail the form][corporate-cla]. -->\n\n\n<!-- [angular-group]: https://groups.google.com/forum/#!forum/angular -->\n<!-- [coc]: https://github.com/angular/code-of-conduct/blob/master/CODE_OF_CONDUCT.md -->\n[commit-message-format]: https://docs.google.com/document/d/1QrDFcIiPjSLDn3EL15IJygNPiHORgU1_OOAqWjiDU5Y/edit#\n[corporate-cla]: http://code.google.com/legal/corporate-cla-v1.0.html\n[dev-doc]: https://github.com/nestjs/nest/blob/master/docs/DEVELOPER.md\n[github]: https://github.com/nestjs/nest\n[discord]: https://discord.gg/nestjs\n[individual-cla]: http://code.google.com/legal/individual-cla-v1.0.html\n[js-style-guide]: https://google.github.io/styleguide/jsguide.html\n[jsfiddle]: http://jsfiddle.net\n[plunker]: http://plnkr.co/edit\n[runnable]: http://runnable.com\n<!-- [stackoverflow]: http://stackoverflow.com/questions/tagged/angular -->\n"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2017-2022 Kamil Mysliwiec <https://kamilmysliwiec.com>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "<p align=\"center\">\n  <a href=\"http://nestjs.com/\" target=\"blank\"><img src=\"https://nestjs.com/img/logo-small.svg\" width=\"120\" alt=\"Nest Logo\" /></a>\n</p>\n\n[travis-image]: https://api.travis-ci.org/nestjs/nest.svg?branch=master\n[travis-url]: https://travis-ci.org/nestjs/nest\n[linux-image]: https://img.shields.io/travis/nestjs/nest/master.svg?label=linux\n[linux-url]: https://travis-ci.org/nestjs/nest\n\n  <p align=\"center\">A progressive <a href=\"http://nodejs.org\" target=\"blank\">Node.js</a> framework for building efficient and scalable server-side applications.</p>\n    <p align=\"center\">\n<a href=\"https://www.npmjs.com/~nestjscore\"><img src=\"https://img.shields.io/npm/v/@nestjs/core.svg\" alt=\"NPM Version\" /></a>\n<a href=\"https://www.npmjs.com/~nestjscore\"><img src=\"https://img.shields.io/npm/l/@nestjs/core.svg\" alt=\"Package License\" /></a>\n<a href=\"https://www.npmjs.com/~nestjscore\"><img src=\"https://img.shields.io/npm/dm/@nestjs/core.svg\" alt=\"NPM Downloads\" /></a>\n<a href=\"https://discord.gg/G7Qnnhy\" target=\"_blank\"><img src=\"https://img.shields.io/badge/discord-online-brightgreen.svg\" alt=\"Discord\"/></a>\n<a href=\"https://opencollective.com/nest#backer\"><img src=\"https://opencollective.com/nest/backers/badge.svg\" alt=\"Backers on Open Collective\" /></a>\n<a href=\"https://opencollective.com/nest#sponsor\"><img src=\"https://opencollective.com/nest/sponsors/badge.svg\" alt=\"Sponsors on Open Collective\" /></a>\n  <a href=\"https://paypal.me/kamilmysliwiec\"><img src=\"https://img.shields.io/badge/Donate-PayPal-dc3d53.svg\"/></a>\n  <a href=\"https://twitter.com/nestframework\"><img src=\"https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow\"></a>\n</p>\n  <!--[![Backers on Open Collective](https://opencollective.com/nest/backers/badge.svg)](https://opencollective.com/nest#backer)\n  [![Sponsors on Open Collective](https://opencollective.com/nest/sponsors/badge.svg)](https://opencollective.com/nest#sponsor)-->\n\n## Description\n\n[Mongoose](http://mongoosejs.com/) module for [Nest](https://github.com/nestjs/nest).\n\n## Installation\n\n```bash\n$ npm i --save @nestjs/mongoose mongoose\n```\n\n## Quick Start\n\n[Overview & Tutorial](https://docs.nestjs.com/techniques/mongodb)\n\n## Support\n\nNest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).\n\n## Stay in touch\n\n* Author - [Kamil Myśliwiec](https://twitter.com/kammysliwiec)\n* Website - [https://nestjs.com](https://nestjs.com/)\n* Twitter - [@nestframework](https://twitter.com/nestframework)\n\n## License\n\nNest is [MIT licensed](LICENSE).\n"
  },
  {
    "path": "docker-compose.yml",
    "content": "version: \"3\"\n\nservices:\n  mongodb:\n    image: mongo:latest\n    environment:\n      - MONGODB_DATABASE=\"test\"\n    ports:\n      - 27017:27017"
  },
  {
    "path": "eslint.config.mjs",
    "content": "// @ts-check\nimport eslint from '@eslint/js';\nimport eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended';\nimport globals from 'globals';\nimport tseslint from 'typescript-eslint';\n\nexport default tseslint.config(\n  {\n    ignores: [],\n  },\n  eslint.configs.recommended,\n  ...tseslint.configs.recommendedTypeChecked,\n  eslintPluginPrettierRecommended,\n  {\n    languageOptions: {\n      globals: {\n        ...globals.node,\n        ...globals.jest,\n      },\n      ecmaVersion: 5,\n      sourceType: 'module',\n      parserOptions: {\n        projectService: true,\n        tsconfigRootDir: import.meta.dirname,\n      },\n    },\n  },\n  {\n    rules: {\n      '@typescript-eslint/no-explicit-any': 'off',\n      '@typescript-eslint/no-unsafe-assignment': 'off',\n      '@typescript-eslint/no-unsafe-call': 'off',\n      '@typescript-eslint/no-unsafe-member-access': 'off',\n      '@typescript-eslint/no-unsafe-function-type': 'off',\n      '@typescript-eslint/no-unsafe-argument': 'off',\n      '@typescript-eslint/no-unsafe-return': 'off',\n      '@typescript-eslint/require-await': 'warn',\n      '@typescript-eslint/no-misused-promises': 'warn',\n      'no-self-assign': 'warn',\n      '@typescript-eslint/restrict-template-expressions': 'warn',\n      '@typescript-eslint/no-redundant-type-constituents': 'warn'\n    },\n  },\n);"
  },
  {
    "path": "lib/common/index.ts",
    "content": "export * from './mongoose.decorators';\nexport { getConnectionToken, getModelToken } from './mongoose.utils';\n"
  },
  {
    "path": "lib/common/mongoose.decorators.ts",
    "content": "import { Inject } from '@nestjs/common';\nimport { getConnectionToken, getModelToken } from './mongoose.utils';\n\n/**\n * @publicApi\n */\nexport const InjectModel = (model: string, connectionName?: string) =>\n  Inject(getModelToken(model, connectionName));\n\n/**\n * @publicApi\n */\nexport const InjectConnection = (name?: string) =>\n  Inject(getConnectionToken(name));\n"
  },
  {
    "path": "lib/common/mongoose.utils.ts",
    "content": "import { Logger } from '@nestjs/common';\nimport { Observable } from 'rxjs';\nimport { delay, retryWhen, scan } from 'rxjs/operators';\nimport { DEFAULT_DB_CONNECTION } from '../mongoose.constants';\n\n/**\n * @publicApi\n */\nexport function getModelToken(model: string, connectionName?: string) {\n  if (connectionName === undefined) {\n    return `${model}Model`;\n  }\n  return `${getConnectionToken(connectionName)}/${model}Model`;\n}\n\n/**\n * @publicApi\n */\nexport function getConnectionToken(name?: string) {\n  return name && name !== DEFAULT_DB_CONNECTION\n    ? `${name}Connection`\n    : DEFAULT_DB_CONNECTION;\n}\n\nexport function handleRetry(\n  retryAttempts = 9,\n  retryDelay = 3000,\n  verboseRetryLog = false,\n): <T>(source: Observable<T>) => Observable<T> {\n  const logger = new Logger('MongooseModule');\n  return <T>(source: Observable<T>) =>\n    source.pipe(\n      retryWhen((e) =>\n        e.pipe(\n          scan((errorCount, error) => {\n            const verboseMessage = verboseRetryLog\n              ? ` Message: ${error.message}.`\n              : '';\n            const retryMessage =\n              retryAttempts > 0 ? ` Retrying (${errorCount + 1})...` : '';\n\n            logger.error(\n              [\n                'Unable to connect to the database.',\n                verboseMessage,\n                retryMessage,\n              ].join(''),\n              error.stack,\n            );\n            if (errorCount + 1 >= retryAttempts) {\n              throw error;\n            }\n            return errorCount + 1;\n          }, 0),\n          delay(retryDelay),\n        ),\n      ),\n    );\n}\n"
  },
  {
    "path": "lib/decorators/index.ts",
    "content": "export * from './prop.decorator';\nexport * from './schema.decorator';\nexport * from './virtual.decorator';\n"
  },
  {
    "path": "lib/decorators/prop.decorator.ts",
    "content": "import * as mongoose from 'mongoose';\nimport { CannotDetermineTypeError } from '../errors';\nimport { RAW_OBJECT_DEFINITION } from '../mongoose.constants';\nimport { TypeMetadataStorage } from '../storages/type-metadata.storage';\n\nconst TYPE_METADATA_KEY = 'design:type';\n/**\n * Interface defining property options that can be passed to `@Prop()` decorator.\n */\nexport type PropOptions<T = any> =\n  | Partial<mongoose.SchemaDefinitionProperty<T>>\n  | mongoose.SchemaType;\n\n/**\n * @Prop decorator is used to mark a specific class property as a Mongoose property.\n * Only properties decorated with this decorator will be defined in the schema.\n * \n * @publicApi\n */\nexport function Prop(options?: PropOptions): PropertyDecorator {\n  return (target: object, propertyKey: string | symbol) => {\n    options = (options || {}) as mongoose.SchemaTypeOptions<unknown>;\n\n    const isRawDefinition = options[RAW_OBJECT_DEFINITION];\n    if (!options.type && !Array.isArray(options) && !isRawDefinition) {\n      const type = Reflect.getMetadata(TYPE_METADATA_KEY, target, propertyKey);\n\n      if (type === Array) {\n        options.type = [];\n      } else if (type && type !== Object) {\n        options.type = type;\n      } else {\n        throw new CannotDetermineTypeError(\n          target.constructor?.name,\n          propertyKey as string,\n        );\n      }\n    }\n\n    TypeMetadataStorage.addPropertyMetadata({\n      target: target.constructor,\n      propertyKey: propertyKey as string,\n      options: options as PropOptions,\n    });\n  };\n}\n"
  },
  {
    "path": "lib/decorators/schema.decorator.ts",
    "content": "import * as mongoose from 'mongoose';\nimport { TypeMetadataStorage } from '../storages/type-metadata.storage';\n\n/**\n * Interface defining schema options that can be passed to `@Schema()` decorator.\n */\nexport type SchemaOptions = mongoose.SchemaOptions;\n\n/**\n * @Schema decorator is used to mark a class as a Mongoose schema.\n * Only properties decorated with this decorator will be defined in the schema.\n * \n * @publicApi\n */\nexport function Schema(options?: SchemaOptions): ClassDecorator {\n  return (target: Function) => {\n    TypeMetadataStorage.addSchemaMetadata({\n      target,\n      options,\n    });\n  };\n}\n"
  },
  {
    "path": "lib/decorators/virtual.decorator.ts",
    "content": "import { VirtualTypeOptions } from 'mongoose';\nimport { TypeMetadataStorage } from '../storages/type-metadata.storage';\n\n/**\n * Interface defining the options that can be passed to the `@Virtual()` decorator.\n * \n * @publicApi\n */\nexport interface VirtualOptions {\n  /**\n   * The options to pass to the virtual type.\n   */\n  options?: VirtualTypeOptions;\n  /**\n   * The sub path to use for the virtual.\n   * Defaults to the property key.\n   */\n  subPath?: string;\n  /**\n   * The getter function to use for the virtual.\n   */\n  get?: (...args: any[]) => any;\n  /**\n   * The setter function to use for the virtual.\n   */\n  set?: (...args: any[]) => any;\n}\n\n/**\n * The Virtual decorator marks a class property as a Mongoose virtual.\n * \n * @publicApi\n */\nexport function Virtual(options?: VirtualOptions): PropertyDecorator {\n  return (target: object, propertyKey: string | symbol) => {\n    TypeMetadataStorage.addVirtualMetadata({\n      target: target.constructor,\n      options: options?.options,\n      name:\n        propertyKey.toString() +\n        (options?.subPath ? `.${options.subPath}` : ''),\n      setter: options?.set,\n      getter: options?.get,\n    });\n  };\n}\n"
  },
  {
    "path": "lib/errors/cannot-determine-type.error.ts",
    "content": "export class CannotDetermineTypeError extends Error {\n  constructor(hostClass: string, propertyKey: string) {\n    super(\n      `Cannot determine a type for the \"${hostClass}.${propertyKey}\" field (union/intersection/ambiguous type was used). Make sure your property is decorated with a \"@Prop({ type: TYPE_HERE })\" decorator.`,\n    );\n  }\n}\n"
  },
  {
    "path": "lib/errors/index.ts",
    "content": "export * from './cannot-determine-type.error';\n"
  },
  {
    "path": "lib/factories/definitions.factory.ts",
    "content": "import { Type } from '@nestjs/common';\nimport { isUndefined } from '@nestjs/common/utils/shared.utils';\nimport * as mongoose from 'mongoose';\nimport { PropOptions } from '../decorators';\nimport { TypeMetadataStorage } from '../storages/type-metadata.storage';\n\nconst BUILT_IN_TYPES: Function[] = [\n  Boolean,\n  Number,\n  String,\n  Map,\n  Date,\n  Buffer,\n  BigInt,\n];\n\nexport class DefinitionsFactory {\n  static createForClass(target: Type<unknown>): mongoose.SchemaDefinition {\n    if (!target) {\n      throw new Error(\n        `Target class \"${target}\" passed in to the \"DefinitionsFactory#createForClass()\" method is \"undefined\".`,\n      );\n    }\n    let schemaDefinition: mongoose.SchemaDefinition = {};\n    let parent: Function = target;\n\n    while (!isUndefined(parent.prototype)) {\n      if (parent === Function.prototype) {\n        break;\n      }\n      const schemaMetadata = TypeMetadataStorage.getSchemaMetadataByTarget(\n        parent as Type<unknown>,\n      );\n      if (!schemaMetadata) {\n        parent = Object.getPrototypeOf(parent);\n        continue;\n      }\n      schemaMetadata.properties?.forEach((item) => {\n        const options = this.inspectTypeDefinition(item.options as any);\n        this.inspectRef(item.options as any);\n\n        schemaDefinition = {\n          [item.propertyKey]: options as any,\n          ...schemaDefinition,\n        };\n      });\n      parent = Object.getPrototypeOf(parent);\n    }\n\n    return schemaDefinition;\n  }\n\n  private static inspectTypeDefinition(\n    optionsOrType: mongoose.SchemaTypeOptions<unknown> | Function,\n  ): PropOptions | [PropOptions] | Function | mongoose.Schema {\n    if (typeof optionsOrType === 'function') {\n      if (this.isPrimitive(optionsOrType)) {\n        return optionsOrType;\n      } else if (this.isMongooseSchemaType(optionsOrType)) {\n        return optionsOrType;\n      }\n      const isClass = /^class\\s/.test(\n        Function.prototype.toString.call(optionsOrType),\n      );\n      optionsOrType = isClass ? optionsOrType : optionsOrType();\n\n      const schemaDefinition = this.createForClass(\n        optionsOrType as Type<unknown>,\n      );\n      const schemaMetadata = TypeMetadataStorage.getSchemaMetadataByTarget(\n        optionsOrType as Type<unknown>,\n      );\n      if (schemaMetadata?.options) {\n        /**\n         * When options are provided (e.g., `@Schema({ timestamps: true })`)\n         * create a new nested schema for a subdocument\n         * @ref https://mongoosejs.com/docs/subdocs.html\n         **/\n\n        return new mongoose.Schema(\n          schemaDefinition,\n          schemaMetadata.options,\n        ) as mongoose.Schema;\n      }\n      return schemaDefinition;\n    } else if (\n      typeof optionsOrType.type === 'function' ||\n      (Array.isArray(optionsOrType.type) &&\n        typeof optionsOrType.type[0] === 'function')\n    ) {\n      optionsOrType.type = this.inspectTypeDefinition(optionsOrType.type);\n      return optionsOrType;\n    } else if (Array.isArray(optionsOrType)) {\n      return optionsOrType.length > 0\n        ? [this.inspectTypeDefinition(optionsOrType[0])]\n        : (optionsOrType as any);\n    }\n    return optionsOrType;\n  }\n\n  private static inspectRef(\n    optionsOrType: mongoose.SchemaTypeOptions<unknown> | Function,\n  ) {\n    if (!optionsOrType || typeof optionsOrType !== 'object') {\n      return;\n    }\n    if (typeof optionsOrType?.ref === 'function') {\n      try {\n        const result = (optionsOrType.ref as Function)();\n        if (typeof result?.name === 'string') {\n          optionsOrType.ref = result.name;\n        }\n        optionsOrType.ref = optionsOrType.ref;\n      } catch (err) {\n        if (err instanceof TypeError) {\n          const refClassName = (optionsOrType.ref as Function)?.name;\n          throw new Error(\n            `Unsupported syntax: Class constructor \"${refClassName}\" cannot be invoked without 'new'. Make sure to wrap your class reference in an arrow function (for example, \"ref: () => ${refClassName}\").`,\n          );\n        }\n        throw err;\n      }\n    } else if (Array.isArray(optionsOrType.type)) {\n      if (optionsOrType.type.length > 0) {\n        this.inspectRef(optionsOrType.type[0]);\n      }\n    }\n  }\n\n  private static isPrimitive(type: Function) {\n    return BUILT_IN_TYPES.includes(type);\n  }\n\n  private static isMongooseSchemaType(type: Function) {\n    if (!type || !type.prototype) {\n      return false;\n    }\n    const prototype = Object.getPrototypeOf(type.prototype);\n    return prototype && prototype.constructor === mongoose.SchemaType;\n  }\n}\n"
  },
  {
    "path": "lib/factories/index.ts",
    "content": "export * from './definitions.factory';\nexport * from './schema.factory';\nexport * from './virtuals.factory';\n"
  },
  {
    "path": "lib/factories/schema.factory.ts",
    "content": "import { Type } from '@nestjs/common';\nimport * as mongoose from 'mongoose';\nimport { SchemaDefinition, SchemaDefinitionType } from 'mongoose';\nimport { TypeMetadataStorage } from '../storages/type-metadata.storage';\nimport { DefinitionsFactory } from './definitions.factory';\nimport { VirtualsFactory } from './virtuals.factory';\n\n/**\n * @publicApi\n */\nexport class SchemaFactory {\n  static createForClass<TClass = any>(\n    target: Type<TClass>,\n  ): mongoose.Schema<TClass> {\n    const schemaDefinition = DefinitionsFactory.createForClass(target);\n    const schemaMetadata =\n      TypeMetadataStorage.getSchemaMetadataByTarget(target);\n    const schemaOpts = schemaMetadata?.options;\n\n    const schema = new mongoose.Schema<TClass>(\n      schemaDefinition as SchemaDefinition<SchemaDefinitionType<TClass>>,\n      schemaOpts as mongoose.SchemaOptions<any>,\n    );\n\n    VirtualsFactory.inspect(target, schema);\n\n    return schema;\n  }\n}\n"
  },
  {
    "path": "lib/factories/virtuals.factory.ts",
    "content": "import { Type } from '@nestjs/common';\nimport { isUndefined } from '@nestjs/common/utils/shared.utils';\nimport * as mongoose from 'mongoose';\nimport { TypeMetadataStorage } from '../storages/type-metadata.storage';\n\n/**\n * @publicApi\n */\nexport class VirtualsFactory {\n  static inspect<TClass = any>(\n    target: Type<TClass>,\n    schema: mongoose.Schema<TClass>,\n  ): void {\n    let parent = target;\n\n    while (!isUndefined(parent.prototype)) {\n      if (parent === Function.prototype) {\n        break;\n      }\n      const virtuals = TypeMetadataStorage.getVirtualsMetadataByTarget(parent);\n\n      virtuals.forEach(({ options, name, getter, setter }) => {\n        const virtual = schema.virtual(name, options);\n\n        if (getter) {\n          virtual.get(getter);\n        }\n\n        if (setter) {\n          virtual.set(setter);\n        }\n      });\n\n      parent = Object.getPrototypeOf(parent);\n    }\n  }\n}\n"
  },
  {
    "path": "lib/index.ts",
    "content": "export * from './common';\nexport * from './decorators';\nexport * from './errors';\nexport * from './factories';\nexport * from './interfaces';\nexport * from './mongoose.module';\nexport * from './pipes';\nexport * from './utils';\n"
  },
  {
    "path": "lib/interfaces/async-model-factory.interface.ts",
    "content": "import { ModuleMetadata } from '@nestjs/common';\nimport { ModelDefinition } from './model-definition.interface';\n\n/**\n * @publicApi\n */\nexport interface AsyncModelFactory\n  extends Pick<ModuleMetadata, 'imports'>,\n    Pick<ModelDefinition, 'name' | 'collection' | 'discriminators'> {\n  useFactory: (\n    ...args: any[]\n  ) => ModelDefinition['schema'] | Promise<ModelDefinition['schema']>;\n  inject?: any[];\n}\n"
  },
  {
    "path": "lib/interfaces/index.ts",
    "content": "export * from './async-model-factory.interface';\nexport * from './model-definition.interface';\nexport * from './mongoose-options.interface';\n"
  },
  {
    "path": "lib/interfaces/model-definition.interface.ts",
    "content": "import { Schema } from 'mongoose';\n\n/**\n * @publicApi\n */\nexport type DiscriminatorOptions = {\n  name: string;\n  schema: Schema;\n  value?: string;\n};\n\n\n/**\n * @publicApi\n */\nexport type ModelDefinition = {\n  name: string;\n  schema: any;\n  collection?: string;\n  discriminators?: DiscriminatorOptions[];\n};\n"
  },
  {
    "path": "lib/interfaces/mongoose-options.interface.ts",
    "content": "import { ModuleMetadata, Type } from '@nestjs/common';\nimport { ConnectOptions, Connection, MongooseError } from 'mongoose';\n\n/**\n * @publicApi\n */\nexport interface MongooseModuleOptions extends ConnectOptions {\n  uri?: string;\n  retryAttempts?: number;\n  retryDelay?: number;\n  connectionName?: string;\n  connectionFactory?: (connection: any, name: string) => any;\n  connectionErrorFactory?: (error: MongooseError) => MongooseError;\n  lazyConnection?: boolean;\n  onConnectionCreate?: (connection: Connection) => void;\n  /**\n   * If `true`, will show verbose error messages on each connection retry.\n   */\n  verboseRetryLog?: boolean;\n}\n\n/**\n * @publicApi\n */\nexport interface MongooseOptionsFactory {\n  createMongooseOptions():\n    | Promise<MongooseModuleOptions>\n    | MongooseModuleOptions;\n}\n\n/**\n * @publicApi\n */\nexport type MongooseModuleFactoryOptions = Omit<\n  MongooseModuleOptions,\n  'connectionName'\n>;\n\n/**\n * @publicApi\n */\nexport interface MongooseModuleAsyncOptions\n  extends Pick<ModuleMetadata, 'imports'> {\n  connectionName?: string;\n  useExisting?: Type<MongooseOptionsFactory>;\n  useClass?: Type<MongooseOptionsFactory>;\n  useFactory?: (\n    ...args: any[]\n  ) => Promise<MongooseModuleFactoryOptions> | MongooseModuleFactoryOptions;\n  inject?: any[];\n}\n"
  },
  {
    "path": "lib/metadata/property-metadata.interface.ts",
    "content": "import { PropOptions } from '../decorators/prop.decorator';\n\nexport interface PropertyMetadata {\n  target: Function;\n  propertyKey: string;\n  options: PropOptions;\n}\n"
  },
  {
    "path": "lib/metadata/schema-metadata.interface.ts",
    "content": "import * as mongoose from 'mongoose';\nimport { PropertyMetadata } from './property-metadata.interface';\n\nexport interface SchemaMetadata {\n  target: Function;\n  options?: mongoose.SchemaOptions;\n  properties?: PropertyMetadata[];\n}\n"
  },
  {
    "path": "lib/metadata/virtual-metadata.interface.ts",
    "content": "import { VirtualTypeOptions } from 'mongoose';\n\nexport interface VirtualMetadataInterface {\n  target: Function;\n  name: string;\n  options?: VirtualTypeOptions;\n  getter?: (...args: any[]) => any;\n  setter?: (...args: any[]) => any;\n}\n"
  },
  {
    "path": "lib/mongoose-core.module.ts",
    "content": "import {\n  DynamicModule,\n  Global,\n  Inject,\n  Module,\n  OnApplicationShutdown,\n  Provider,\n  Type,\n} from '@nestjs/common';\nimport { ModuleRef } from '@nestjs/core';\nimport * as mongoose from 'mongoose';\nimport { ConnectOptions, Connection } from 'mongoose';\nimport { defer, lastValueFrom } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\nimport { getConnectionToken, handleRetry } from './common/mongoose.utils';\nimport {\n  MongooseModuleAsyncOptions,\n  MongooseModuleFactoryOptions,\n  MongooseModuleOptions,\n  MongooseOptionsFactory,\n} from './interfaces/mongoose-options.interface';\nimport {\n  MONGOOSE_CONNECTION_NAME,\n  MONGOOSE_MODULE_OPTIONS,\n} from './mongoose.constants';\n\n@Global()\n@Module({})\nexport class MongooseCoreModule implements OnApplicationShutdown {\n  constructor(\n    @Inject(MONGOOSE_CONNECTION_NAME) private readonly connectionName: string,\n    private readonly moduleRef: ModuleRef,\n  ) {}\n\n  static forRoot(\n    uri: string,\n    options: MongooseModuleOptions = {},\n  ): DynamicModule {\n    const {\n      retryAttempts,\n      retryDelay,\n      connectionName,\n      connectionFactory,\n      connectionErrorFactory,\n      lazyConnection,\n      onConnectionCreate,\n      verboseRetryLog,\n      ...mongooseOptions\n    } = options;\n\n    const mongooseConnectionFactory =\n      connectionFactory || ((connection) => connection);\n\n    const mongooseConnectionError =\n      connectionErrorFactory || ((error) => error);\n\n    const mongooseConnectionName = getConnectionToken(connectionName);\n\n    const mongooseConnectionNameProvider = {\n      provide: MONGOOSE_CONNECTION_NAME,\n      useValue: mongooseConnectionName,\n    };\n\n    const connectionProvider = {\n      provide: mongooseConnectionName,\n      useFactory: async (): Promise<any> =>\n        await lastValueFrom(\n          defer(async () =>\n            mongooseConnectionFactory(\n              await this.createMongooseConnection(uri, mongooseOptions, {\n                lazyConnection,\n                onConnectionCreate,\n              }),\n              mongooseConnectionName,\n            ),\n          ).pipe(\n            handleRetry(retryAttempts, retryDelay, verboseRetryLog),\n            catchError((error) => {\n              throw mongooseConnectionError(error);\n            }),\n          ),\n        ),\n    };\n    return {\n      module: MongooseCoreModule,\n      providers: [connectionProvider, mongooseConnectionNameProvider],\n      exports: [connectionProvider],\n    };\n  }\n\n  static forRootAsync(options: MongooseModuleAsyncOptions): DynamicModule {\n    const mongooseConnectionName = getConnectionToken(options.connectionName);\n\n    const mongooseConnectionNameProvider = {\n      provide: MONGOOSE_CONNECTION_NAME,\n      useValue: mongooseConnectionName,\n    };\n\n    const connectionProvider = {\n      provide: mongooseConnectionName,\n      useFactory: async (\n        mongooseModuleOptions: MongooseModuleFactoryOptions,\n      ): Promise<any> => {\n        const {\n          retryAttempts,\n          retryDelay,\n          uri,\n          connectionFactory,\n          connectionErrorFactory,\n          lazyConnection,\n          onConnectionCreate,\n          verboseRetryLog,\n          ...mongooseOptions\n        } = mongooseModuleOptions;\n\n        const mongooseConnectionFactory =\n          connectionFactory || ((connection) => connection);\n\n        const mongooseConnectionError =\n          connectionErrorFactory || ((error) => error);\n\n        return await lastValueFrom(\n          defer(async () =>\n            mongooseConnectionFactory(\n              await this.createMongooseConnection(\n                uri as string,\n                mongooseOptions,\n                { lazyConnection, onConnectionCreate },\n              ),\n              mongooseConnectionName,\n            ),\n          ).pipe(\n            handleRetry(retryAttempts, retryDelay, verboseRetryLog),\n            catchError((error) => {\n              throw mongooseConnectionError(error);\n            }),\n          ),\n        );\n      },\n      inject: [MONGOOSE_MODULE_OPTIONS],\n    };\n    const asyncProviders = this.createAsyncProviders(options);\n    return {\n      module: MongooseCoreModule,\n      imports: options.imports,\n      providers: [\n        ...asyncProviders,\n        connectionProvider,\n        mongooseConnectionNameProvider,\n      ],\n      exports: [connectionProvider],\n    };\n  }\n\n  private static createAsyncProviders(\n    options: MongooseModuleAsyncOptions,\n  ): Provider[] {\n    if (options.useExisting || options.useFactory) {\n      return [this.createAsyncOptionsProvider(options)];\n    }\n    const useClass = options.useClass as Type<MongooseOptionsFactory>;\n    return [\n      this.createAsyncOptionsProvider(options),\n      {\n        provide: useClass,\n        useClass,\n      },\n    ];\n  }\n\n  private static createAsyncOptionsProvider(\n    options: MongooseModuleAsyncOptions,\n  ): Provider {\n    if (options.useFactory) {\n      return {\n        provide: MONGOOSE_MODULE_OPTIONS,\n        useFactory: options.useFactory,\n        inject: options.inject || [],\n      };\n    }\n    // `as Type<MongooseOptionsFactory>` is a workaround for microsoft/TypeScript#31603\n    const inject = [\n      (options.useClass || options.useExisting) as Type<MongooseOptionsFactory>,\n    ];\n    return {\n      provide: MONGOOSE_MODULE_OPTIONS,\n      useFactory: async (optionsFactory: MongooseOptionsFactory) =>\n        await optionsFactory.createMongooseOptions(),\n      inject,\n    };\n  }\n\n  private static async createMongooseConnection(\n    uri: string,\n    mongooseOptions: ConnectOptions,\n    factoryOptions: {\n      lazyConnection?: boolean;\n      onConnectionCreate?: MongooseModuleOptions['onConnectionCreate'];\n    },\n  ): Promise<Connection> {\n    const connection = mongoose.createConnection(uri, mongooseOptions);\n\n    if (factoryOptions?.lazyConnection) {\n      return connection;\n    }\n\n    factoryOptions?.onConnectionCreate?.(connection);\n\n    return connection.asPromise();\n  }\n\n  async onApplicationShutdown() {\n    const connection = this.moduleRef.get<any>(this.connectionName);\n    if (connection) {\n      await connection.close();\n    }\n  }\n}\n"
  },
  {
    "path": "lib/mongoose.constants.ts",
    "content": "export const DEFAULT_DB_CONNECTION = 'DatabaseConnection';\nexport const MONGOOSE_MODULE_OPTIONS = 'MongooseModuleOptions';\nexport const MONGOOSE_CONNECTION_NAME = 'MongooseConnectionName';\n\nexport const RAW_OBJECT_DEFINITION = 'RAW_OBJECT_DEFINITION';\n"
  },
  {
    "path": "lib/mongoose.module.ts",
    "content": "import { DynamicModule, flatten, Module } from '@nestjs/common';\nimport { AsyncModelFactory, ModelDefinition } from './interfaces';\nimport {\n  MongooseModuleAsyncOptions,\n  MongooseModuleOptions,\n} from './interfaces/mongoose-options.interface';\nimport { MongooseCoreModule } from './mongoose-core.module';\nimport {\n  createMongooseAsyncProviders,\n  createMongooseProviders,\n} from './mongoose.providers';\n\n/**\n * @publicApi\n */\n@Module({})\nexport class MongooseModule {\n  static forRoot(\n    uri: string,\n    options: MongooseModuleOptions = {},\n  ): DynamicModule {\n    return {\n      module: MongooseModule,\n      imports: [MongooseCoreModule.forRoot(uri, options)],\n    };\n  }\n\n  static forRootAsync(options: MongooseModuleAsyncOptions): DynamicModule {\n    return {\n      module: MongooseModule,\n      imports: [MongooseCoreModule.forRootAsync(options)],\n    };\n  }\n\n  static forFeature(\n    models: ModelDefinition[] = [],\n    connectionName?: string,\n  ): DynamicModule {\n    const providers = createMongooseProviders(connectionName, models);\n    return {\n      module: MongooseModule,\n      providers: providers,\n      exports: providers,\n    };\n  }\n\n  static forFeatureAsync(\n    factories: AsyncModelFactory[] = [],\n    connectionName?: string,\n  ): DynamicModule {\n    const providers = createMongooseAsyncProviders(connectionName, factories);\n    const imports = factories.map((factory) => factory.imports || []);\n    const uniqImports = new Set(flatten(imports));\n\n    return {\n      module: MongooseModule,\n      imports: [...uniqImports],\n      providers: providers,\n      exports: providers,\n    };\n  }\n}\n"
  },
  {
    "path": "lib/mongoose.providers.ts",
    "content": "import { Provider } from '@nestjs/common';\nimport { Connection, Document, Model } from 'mongoose';\nimport { getConnectionToken, getModelToken } from './common/mongoose.utils';\nimport { AsyncModelFactory, ModelDefinition } from './interfaces';\n\nexport function createMongooseProviders(\n  connectionName?: string,\n  options: ModelDefinition[] = [],\n): Provider[] {\n  return options.reduce(\n    (providers, option) => [\n      ...providers,\n      ...(option.discriminators || []).map((d) => ({\n        provide: getModelToken(d.name, connectionName),\n        useFactory: (model: Model<Document>) =>\n          model.discriminator(d.name, d.schema, d.value),\n        inject: [getModelToken(option.name, connectionName)],\n      })),\n      {\n        provide: getModelToken(option.name, connectionName),\n        useFactory: (connection: Connection) => {\n          const model = connection.models[option.name]\n            ? connection.models[option.name]\n            : connection.model(option.name, option.schema, option.collection);\n          return model;\n        },\n        inject: [getConnectionToken(connectionName)],\n      },\n    ],\n    [] as Provider[],\n  );\n}\n\nexport function createMongooseAsyncProviders(\n  connectionName?: string,\n  modelFactories: AsyncModelFactory[] = [],\n): Provider[] {\n  return modelFactories.reduce((providers, option) => {\n    return [\n      ...providers,\n      {\n        provide: getModelToken(option.name, connectionName),\n        useFactory: async (connection: Connection, ...args: unknown[]) => {\n          const schema = await option.useFactory(...args);\n          const model = connection.model(\n            option.name,\n            schema,\n            option.collection,\n          );\n          return model;\n        },\n        inject: [getConnectionToken(connectionName), ...(option.inject || [])],\n      },\n      ...(option.discriminators || []).map((d) => ({\n        provide: getModelToken(d.name, connectionName),\n        useFactory: (model: Model<Document>) =>\n          model.discriminator(d.name, d.schema, d.value),\n        inject: [getModelToken(option.name, connectionName)],\n      })),\n    ];\n  }, [] as Provider[]);\n}\n"
  },
  {
    "path": "lib/pipes/index.ts",
    "content": "export * from './is-object-id.pipe';\nexport * from './parse-object-id.pipe';\n"
  },
  {
    "path": "lib/pipes/is-object-id.pipe.ts",
    "content": "import { BadRequestException, Injectable, PipeTransform } from '@nestjs/common';\nimport { Types } from 'mongoose';\n\n@Injectable()\nexport class IsObjectIdPipe implements PipeTransform {\n  transform(value: string): string {\n    const isValidObjectId = Types.ObjectId.isValid(value);\n\n    if (!isValidObjectId) {\n      throw new BadRequestException(\n        `Invalid ObjectId: '${value}' is not a valid MongoDB ObjectId`,\n      );\n    }\n\n    return value;\n  }\n}\n"
  },
  {
    "path": "lib/pipes/parse-object-id.pipe.ts",
    "content": "import { BadRequestException, Injectable, PipeTransform } from '@nestjs/common';\nimport { Types } from 'mongoose';\n\n@Injectable()\nexport class ParseObjectIdPipe implements PipeTransform {\n  transform(value: string): Types.ObjectId {\n    const isValidObjectId = Types.ObjectId.isValid(value);\n\n    if (!isValidObjectId) {\n      throw new BadRequestException(\n        `Invalid ObjectId: '${value}' is not a valid MongoDB ObjectId`,\n      );\n    }\n\n    return new Types.ObjectId(value);\n  }\n}\n"
  },
  {
    "path": "lib/storages/type-metadata.storage.ts",
    "content": "import { Type } from '@nestjs/common';\nimport { PropertyMetadata } from '../metadata/property-metadata.interface';\nimport { SchemaMetadata } from '../metadata/schema-metadata.interface';\nimport { VirtualMetadataInterface } from '../metadata/virtual-metadata.interface';\nimport { isTargetEqual } from '../utils/is-target-equal-util';\n\nexport class TypeMetadataStorageHost {\n  private schemas = new Array<SchemaMetadata>();\n  private properties = new Array<PropertyMetadata>();\n  private virtuals = new Array<VirtualMetadataInterface>();\n\n  addPropertyMetadata(metadata: PropertyMetadata) {\n    this.properties.unshift(metadata);\n  }\n\n  addSchemaMetadata(metadata: SchemaMetadata) {\n    this.compileClassMetadata(metadata);\n    this.schemas.push(metadata);\n  }\n\n  addVirtualMetadata(metadata: VirtualMetadataInterface) {\n    this.virtuals.push(metadata);\n  }\n\n  getSchemaMetadataByTarget(target: Type<unknown>): SchemaMetadata | undefined {\n    return this.schemas.find((item) => item.target === target);\n  }\n\n  getVirtualsMetadataByTarget<TClass>(targetFilter: Type<TClass>) {\n    return this.virtuals.filter(({ target }) => target === targetFilter);\n  }\n\n  private compileClassMetadata(metadata: SchemaMetadata) {\n    const belongsToClass = isTargetEqual.bind(undefined, metadata);\n\n    if (!metadata.properties) {\n      metadata.properties = this.getClassFieldsByPredicate(belongsToClass);\n    }\n  }\n\n  private getClassFieldsByPredicate(\n    belongsToClass: (item: PropertyMetadata) => boolean,\n  ) {\n    return this.properties.filter(belongsToClass);\n  }\n}\n\nconst globalRef = global as any;\nexport const TypeMetadataStorage: TypeMetadataStorageHost =\n  globalRef.MongoTypeMetadataStorage ||\n  (globalRef.MongoTypeMetadataStorage = new TypeMetadataStorageHost());\n"
  },
  {
    "path": "lib/utils/index.ts",
    "content": "export * from './raw.util';\n"
  },
  {
    "path": "lib/utils/is-target-equal-util.ts",
    "content": "export type TargetHost = Record<'target', Function>;\nexport function isTargetEqual<T extends TargetHost, U extends TargetHost>(\n  a: T,\n  b: U,\n) {\n  return (\n    a.target === b.target ||\n    (a.target.prototype\n      ? isTargetEqual({ target: (a.target as any).__proto__ }, b)\n      : false)\n  );\n}\n"
  },
  {
    "path": "lib/utils/raw.util.ts",
    "content": "import { RAW_OBJECT_DEFINITION } from '../mongoose.constants';\n\nexport function raw(definition: Record<string, any>) {\n  Object.defineProperty(definition, RAW_OBJECT_DEFINITION, {\n    value: true,\n    enumerable: false,\n    configurable: false,\n  });\n  return definition;\n}\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"@nestjs/mongoose\",\n  \"version\": \"11.0.4\",\n  \"description\": \"Nest - modern, fast, powerful node.js web framework (@mongoose)\",\n  \"author\": \"Kamil Mysliwiec\",\n  \"repository\": \"https://github.com/nestjs/mongoose.git\",\n  \"license\": \"MIT\",\n  \"main\": \"dist/index.js\",\n  \"types\": \"dist/index.d.ts\",\n  \"scripts\": {\n    \"lint\": \"eslint \\\"lib/**/*.ts\\\" --fix\",\n    \"format\": \"prettier \\\"lib/**/*.ts\\\" --write\",\n    \"build\": \"rm -rf dist && tsc -p tsconfig.build.json\",\n    \"precommit\": \"lint-staged\",\n    \"prepublish:npm\": \"npm run build\",\n    \"publish:npm\": \"npm publish --access public\",\n    \"prepublish:next\": \"npm run build\",\n    \"publish:next\": \"npm publish --access public --tag next\",\n    \"prerelease\": \"npm run build\",\n    \"release\": \"release-it\",\n    \"test:e2e\": \"jest --config ./tests/jest-e2e.json --runInBand\",\n    \"test:e2e:dev\": \"jest --config ./tests/jest-e2e.json --runInBand --watch\",\n    \"prepare\": \"husky\"\n  },\n  \"devDependencies\": {\n    \"@commitlint/cli\": \"20.5.0\",\n    \"@commitlint/config-angular\": \"20.5.0\",\n    \"@eslint/eslintrc\": \"3.3.5\",\n    \"@eslint/js\": \"10.0.1\",\n    \"@nestjs/common\": \"11.1.18\",\n    \"@nestjs/core\": \"11.1.18\",\n    \"@nestjs/platform-express\": \"11.1.18\",\n    \"@nestjs/testing\": \"11.1.18\",\n    \"@types/jest\": \"30.0.0\",\n    \"@types/node\": \"24.12.2\",\n    \"eslint\": \"10.2.0\",\n    \"eslint-config-prettier\": \"10.1.8\",\n    \"eslint-plugin-prettier\": \"5.5.5\",\n    \"globals\": \"17.4.0\",\n    \"husky\": \"9.1.7\",\n    \"jest\": \"30.3.0\",\n    \"lint-staged\": \"16.4.0\",\n    \"mongoose\": \"9.4.1\",\n    \"prettier\": \"3.8.2\",\n    \"reflect-metadata\": \"0.2.2\",\n    \"release-it\": \"19.2.4\",\n    \"rxjs\": \"7.8.2\",\n    \"supertest\": \"7.2.2\",\n    \"ts-jest\": \"29.4.9\",\n    \"ts-node\": \"10.9.2\",\n    \"typescript\": \"5.9.3\",\n    \"typescript-eslint\": \"8.58.1\"\n  },\n  \"peerDependencies\": {\n    \"@nestjs/common\": \"^10.0.0 || ^11.0.0\",\n    \"@nestjs/core\": \"^10.0.0 || ^11.0.0\",\n    \"mongoose\": \"^7.0.0 || ^8.0.0 || ^9.0.0\",\n    \"rxjs\": \"^7.0.0\"\n  },\n  \"lint-staged\": {\n    \"**/*.{ts,json}\": []\n  }\n}\n"
  },
  {
    "path": "renovate.json",
    "content": "{\n  \"semanticCommits\": true,\n  \"packageRules\": [{\n    \"depTypeList\": [\"devDependencies\"],\n    \"automerge\": true\n  }],\n  \"extends\": [\n    \"config:base\"\n  ]\n}\n"
  },
  {
    "path": "tests/e2e/discriminator.spec.ts",
    "content": "import { DynamicModule, HttpStatus, INestApplication } from '@nestjs/common';\nimport { Test } from '@nestjs/testing';\nimport { Server } from 'http';\nimport * as request from 'supertest';\nimport { MongooseModule } from '../../lib';\nimport { EventModule } from '../src/event/event.module';\nimport {\n  ClickLinkEvent,\n  ClieckLinkEventSchema,\n} from '../src/event/schemas/click-link-event.schema';\nimport { Event, EventSchema } from '../src/event/schemas/event.schema';\nimport {\n  SignUpEvent,\n  SignUpEventSchema,\n} from '../src/event/schemas/sign-up-event.schema';\n\nconst testCase: [string, DynamicModule][] = [\n  [\n    'forFeature',\n    MongooseModule.forFeature([\n      {\n        name: Event.name,\n        schema: EventSchema,\n        discriminators: [\n          { name: ClickLinkEvent.name, schema: ClieckLinkEventSchema },\n          { name: SignUpEvent.name, schema: SignUpEventSchema },\n        ],\n      },\n    ]),\n  ],\n  [\n    'forFeatureAsync',\n    MongooseModule.forFeatureAsync([\n      {\n        name: Event.name,\n        useFactory: async () => EventSchema,\n        discriminators: [\n          { name: ClickLinkEvent.name, schema: ClieckLinkEventSchema },\n          { name: SignUpEvent.name, schema: SignUpEventSchema },\n        ],\n      },\n    ]),\n  ],\n];\n\ndescribe.each(testCase)('Discriminator - %s', (_, features) => {\n  let server: Server;\n  let app: INestApplication;\n\n  beforeEach(async () => {\n    const module = await Test.createTestingModule({\n      imports: [\n        MongooseModule.forRoot('mongodb://localhost:27017/test'),\n        EventModule.forFeature(features),\n      ],\n    }).compile();\n\n    app = module.createNestApplication();\n    server = app.getHttpServer();\n    await app.init();\n  });\n\n  afterEach(async () => {\n    await app.close();\n  });\n\n  it(`should return click-link document`, async () => {\n    const createDto = { url: 'http://google.com' };\n    const response = await request(server)\n      .post('/event/click-link')\n      .send(createDto);\n    expect(response.status).toBe(HttpStatus.CREATED);\n    expect(response.body).toMatchObject({\n      ...createDto,\n      kind: expect.any(String),\n      time: expect.any(String),\n    });\n  });\n\n  it(`should return sign-up document`, async () => {\n    const createDto = { user: 'testuser' };\n    const response = await request(server)\n      .post('/event/sign-up')\n      .send(createDto);\n    expect(response.status).toBe(HttpStatus.CREATED);\n    expect(response.body).toMatchObject({\n      ...createDto,\n      kind: expect.any(String),\n      time: expect.any(String),\n    });\n  });\n\n  test.each`\n    path            | payload\n    ${'click-link'} | ${{ testing: 1 }}\n    ${'sign-up'}    | ${{ testing: 1 }}\n  `(`document ($path) should not be created`, async ({ path, payload }) => {\n    const response = await request(server).post(`/event/${path}`).send(payload);\n    expect(response.error).toBeInstanceOf(Error);\n    expect(response.status).toBe(HttpStatus.INTERNAL_SERVER_ERROR);\n  });\n});\n"
  },
  {
    "path": "tests/e2e/mongoose-lazy-connection.spec.ts",
    "content": "import { INestApplication } from '@nestjs/common';\nimport { Test } from '@nestjs/testing';\nimport { Server } from 'http';\nimport * as request from 'supertest';\nimport { LazyAppModule } from '../src/lazy-app.module';\n\ndescribe('Mongoose lazy connection', () => {\n  let server: Server;\n  let app: INestApplication;\n\n  beforeEach(async () => {\n    const module = await Test.createTestingModule({\n      imports: [LazyAppModule],\n    }).compile();\n\n    app = module.createNestApplication();\n    server = app.getHttpServer();\n    await app.init();\n  });\n\n  it(`should return created document`, (done) => {\n    const createDto = { name: 'Nest', breed: 'Maine coon', age: 5 };\n    request(server)\n      .post('/cats')\n      .send(createDto)\n      .expect(201)\n      .end((err, { body }) => {\n        expect(body.name).toEqual(createDto.name);\n        expect(body.age).toEqual(createDto.age);\n        expect(body.breed).toEqual(createDto.breed);\n        done();\n      });\n  });\n\n  afterEach(async () => {\n    await app.close();\n  });\n});\n"
  },
  {
    "path": "tests/e2e/mongoose.spec.ts",
    "content": "import { INestApplication } from '@nestjs/common';\nimport { Test } from '@nestjs/testing';\nimport { Server } from 'http';\nimport * as request from 'supertest';\nimport { AppModule } from '../src/app.module';\nimport { CreateCatDto } from '../src/cats/dto/create-cat.dto';\nimport { Cat } from '../src/cats/schemas/cat.schema';\n\ndescribe('Mongoose', () => {\n  let server: Server;\n  let app: INestApplication;\n\n  beforeEach(async () => {\n    const module = await Test.createTestingModule({\n      imports: [AppModule],\n    }).compile();\n\n    app = module.createNestApplication();\n    server = app.getHttpServer();\n    await app.init();\n  });\n\n  it(`should return created document`, (done) => {\n    const createDto = { name: 'Nest', breed: 'Maine coon', age: 5 };\n    request(server)\n      .post('/cats')\n      .send(createDto)\n      .expect(201)\n      .end((err, { body }) => {\n        expect(body.name).toEqual(createDto.name);\n        expect(body.age).toEqual(createDto.age);\n        expect(body.breed).toEqual(createDto.breed);\n        done();\n      });\n  });\n\n  it('should populate array of kittens', async () => {\n    let createDto: CreateCatDto = {\n      name: 'Kitten',\n      breed: 'Maine coon',\n      age: 1,\n    };\n\n    const kitten: Cat = await new Promise((resolve) => {\n      request(server)\n        .post('/cats')\n        .send(createDto)\n        .expect(201)\n        .end((err, { body }) => {\n          expect(body.name).toEqual(createDto.name);\n          expect(body.age).toEqual(createDto.age);\n          expect(body.breed).toEqual(createDto.breed);\n          resolve(body);\n        });\n    });\n\n    createDto = {\n      ...createDto,\n      name: 'Nest',\n      age: 5,\n      kitten: [kitten._id.toString()],\n    };\n\n    const parent = await new Promise<string>((resolve) => {\n      request(server)\n        .post('/cats')\n        .send(createDto)\n        .expect(201)\n        .end((err, { body }) => {\n          expect(body.name).toEqual(createDto.name);\n          expect(body.age).toEqual(createDto.age);\n          expect(body.breed).toEqual(createDto.breed);\n          resolve(body._id as string);\n        });\n    });\n\n    await new Promise<void>((resolve) => {\n      request(server)\n        .get(`/cat/${parent}`)\n        .expect(200)\n        .end((err, { body }) => {\n          expect(Array.isArray(body.kitten)).toBe(true);\n          expect(body.kitten[0]._id).toBe(kitten._id);\n          expect(body.kitten[0].name).toBe(kitten.name);\n          expect(body.kitten[0].breed).toBe(kitten.breed);\n          expect(body.kitten[0].age).toBe(kitten.age);\n          resolve();\n        });\n    });\n  });\n\n  afterEach(async () => {\n    await app.close();\n  });\n});\n"
  },
  {
    "path": "tests/e2e/schema-definitions.factory.spec.ts",
    "content": "import * as mongoose from 'mongoose';\nimport { DefinitionsFactory, Prop, raw, Schema } from '../../lib';\nimport { CannotDetermineTypeError } from '../../lib/errors';\n\n@Schema()\nclass RefClass {\n  @Prop()\n  title: string;\n\n  @Prop({ type: mongoose.Schema.Types.ObjectId, ref: () => ExampleClass })\n  host;\n}\n\n@Schema()\nclass ChildClass {\n  @Prop()\n  id: number;\n\n  @Prop()\n  name: string;\n}\n\n@Schema()\nclass ExampleClass {\n  @Prop()\n  objectId: mongoose.Schema.Types.ObjectId;\n\n  @Prop({ required: true })\n  name: string;\n\n  @Prop()\n  buffer: mongoose.Schema.Types.Buffer;\n\n  @Prop()\n  decimal: mongoose.Schema.Types.Decimal128;\n\n  @Prop()\n  mixed: mongoose.Schema.Types.Mixed;\n\n  @Prop(\n    raw({\n      expires: 0,\n      type: Date,\n    }),\n  )\n  expiresAt: Date;\n\n  @Prop()\n  map: Map<any, any>;\n\n  @Prop()\n  isEnabled: boolean;\n\n  @Prop()\n  number: number;\n\n  @Prop({\n    type: [{ type: mongoose.Schema.Types.ObjectId, ref: () => RefClass }],\n  })\n  ref: RefClass[];\n\n  @Prop({ required: true })\n  child: ChildClass;\n\n  @Prop({ type: () => ChildClass })\n  child2: ChildClass;\n\n  @Prop([ChildClass])\n  nodes: ChildClass[];\n\n  @Prop([raw({ custom: 'literal', object: true })])\n  customArray: any;\n\n  @Prop(raw({ custom: 'literal', object: true }))\n  customObject: any;\n\n  @Prop({ type: mongoose.Schema.Types.Mixed })\n  any: any;\n\n  @Prop()\n  array: Array<any>;\n\n  @Prop()\n  bigint: bigint;\n}\n\ndescribe('DefinitionsFactory', () => {\n  it('should generate a valid schema definition', () => {\n    const definition = DefinitionsFactory.createForClass(ExampleClass);\n\n    expect(Object.keys(definition)).toEqual([\n      'objectId',\n      'name',\n      'buffer',\n      'decimal',\n      'mixed',\n      'expiresAt',\n      'map',\n      'isEnabled',\n      'number',\n      'ref',\n      'child',\n      'child2',\n      'nodes',\n      'customArray',\n      'customObject',\n      'any',\n      'array',\n      'bigint',\n    ]);\n    expect(definition).toEqual({\n      objectId: {\n        type: mongoose.Schema.Types.ObjectId,\n      },\n      ref: {\n        type: [\n          {\n            ref: 'RefClass',\n            type: mongoose.Schema.Types.ObjectId,\n          },\n        ],\n      },\n      name: {\n        required: true,\n        type: String,\n      },\n      nodes: [\n        {\n          id: {\n            type: Number,\n          },\n          name: {\n            type: String,\n          },\n        },\n      ],\n      bigint: { type: BigInt },\n      buffer: { type: mongoose.Schema.Types.Buffer },\n      decimal: { type: mongoose.Schema.Types.Decimal128 },\n      child: {\n        required: true,\n        type: {\n          id: {\n            type: Number,\n          },\n          name: {\n            type: String,\n          },\n        },\n      },\n      child2: {\n        type: {\n          id: {\n            type: Number,\n          },\n          name: {\n            type: String,\n          },\n        },\n      },\n      any: { type: mongoose.Schema.Types.Mixed },\n      array: { type: [] },\n      customArray: [{ custom: 'literal', object: true }],\n      customObject: { custom: 'literal', object: true },\n      expiresAt: {\n        expires: 0,\n        type: Date,\n      },\n      isEnabled: {\n        type: Boolean,\n      },\n      map: {\n        type: Map,\n      },\n      mixed: { type: mongoose.Schema.Types.Mixed },\n      number: { type: Number },\n    });\n  });\n\n  it('should generate a valid schema definition (class reference) for cyclic deps', () => {\n    const refClassDefinition = DefinitionsFactory.createForClass(RefClass);\n    expect(refClassDefinition).toEqual({\n      host: {\n        ref: 'ExampleClass',\n        type: mongoose.Schema.Types.ObjectId,\n      },\n      title: {\n        type: String,\n      },\n    });\n  });\n\n  it('should throw an error when type is ambiguous', () => {\n    try {\n      class AmbiguousField {\n        @Prop()\n        randomField: object | null;\n      }\n      DefinitionsFactory.createForClass(AmbiguousField);\n    } catch (err) {\n      expect(err).toBeInstanceOf(CannotDetermineTypeError);\n      expect((err as Error).message).toEqual(\n        'Cannot determine a type for the \"AmbiguousField.randomField\" field (union/intersection/ambiguous type was used). Make sure your property is decorated with a \"@Prop({ type: TYPE_HERE })\" decorator.',\n      );\n    }\n  });\n});\n"
  },
  {
    "path": "tests/e2e/schema.factory.spec.ts",
    "content": "import { Prop, Schema, SchemaFactory, Virtual } from '../../lib';\n\n@Schema({ validateBeforeSave: false, _id: true, autoIndex: true })\nclass ChildClass {\n  @Prop()\n  id: number;\n\n  @Prop()\n  name: string;\n}\n\nconst getterFunctionMock = jest.fn();\nconst setterFunctionMock = jest.fn();\n\n@Schema({\n  validateBeforeSave: false,\n  _id: true,\n  autoIndex: true,\n  timestamps: true,\n})\nclass ExampleClass {\n  @Prop({ required: true })\n  children: ChildClass;\n\n  @Prop([ChildClass])\n  nodes: ChildClass[];\n\n  @Prop()\n  array: Array<any>;\n\n  // see https://github.com/nestjs/mongoose/issues/839\n  @Prop({ type: [ChildClass], required: true })\n  anotherArray: ChildClass[];\n\n  @Virtual({\n    options: {\n      localField: 'array',\n      ref: 'ChildClass',\n      foreignField: 'id',\n    },\n  })\n  virtualPropsWithOptions: Array<ChildClass>;\n\n  @Virtual({\n    get: getterFunctionMock,\n    set: setterFunctionMock,\n  })\n  virtualPropsWithGetterSetterFunctions: Array<ChildClass>;\n}\n\ndescribe('SchemaFactory', () => {\n  it('should populate the schema options', () => {\n    const schema = SchemaFactory.createForClass(ExampleClass) as any;\n\n    expect(schema.$timestamps).toBeDefined();\n    expect(schema.options).toEqual(\n      expect.objectContaining({\n        validateBeforeSave: false,\n        _id: true,\n        autoIndex: true,\n        timestamps: true,\n      }),\n    );\n\n    expect(schema.childSchemas[0].schema).toEqual(\n      expect.objectContaining({\n        options: expect.objectContaining({\n          validateBeforeSave: false,\n          _id: true,\n          autoIndex: true,\n        }),\n      }),\n    );\n  });\n\n  it('should add virtuals with corresponding options', () => {\n    const {\n      virtuals: { virtualPropsWithOptions },\n    } = SchemaFactory.createForClass(ExampleClass) as any;\n\n    expect(virtualPropsWithOptions).toEqual(\n      expect.objectContaining({\n        path: 'virtualPropsWithOptions',\n        setters: [expect.any(Function)],\n        getters: [],\n        options: expect.objectContaining({\n          localField: 'array',\n          ref: 'ChildClass',\n          foreignField: 'id',\n        }),\n      }),\n    );\n  });\n\n  it('should add virtuals with corresponding getter and setter functions', () => {\n    const {\n      virtuals: { virtualPropsWithGetterSetterFunctions },\n    } = SchemaFactory.createForClass(ExampleClass) as any;\n\n    expect(virtualPropsWithGetterSetterFunctions).toEqual(\n      expect.objectContaining({\n        path: 'virtualPropsWithGetterSetterFunctions',\n        setters: [setterFunctionMock],\n        getters: [getterFunctionMock],\n        options: {},\n      }),\n    );\n  });\n\n  it('should inherit virtuals from parent classes', () => {\n    @Schema()\n    class ChildClass extends ExampleClass {}\n    const { virtuals } = SchemaFactory.createForClass(ChildClass) as any;\n\n    expect(virtuals.virtualPropsWithOptions).toBeDefined();\n    expect(virtuals.virtualPropsWithGetterSetterFunctions).toBeDefined();\n  });\n});\n"
  },
  {
    "path": "tests/e2e/virtual.factory.spec.ts",
    "content": "import { VirtualsFactory } from '../../lib';\nimport { VirtualMetadataInterface } from '../../lib/metadata/virtual-metadata.interface';\nimport { TypeMetadataStorage } from '../../lib/storages/type-metadata.storage';\n\ndescribe('VirtualsFactory', () => {\n  const setVirtualSetterFunctionMock = jest.fn();\n  const setVirtualGetterFunctionMock = jest.fn();\n  const schemaMock = {\n    virtual: jest.fn(() => ({\n      get: setVirtualGetterFunctionMock,\n      set: setVirtualSetterFunctionMock,\n    })),\n  } as any;\n\n  const targetConstructorMock = jest.fn();\n\n  const virtualOptionsMock = {\n    ref: 'collectionNameMock',\n    localField: 'localFieldMockValue',\n    foreignField: 'foreignFieldMockValue',\n  };\n\n  const virtualMetadataWithOnlyRequiredAttributesMock = {\n    target: targetConstructorMock,\n    name: 'attribute1Mock',\n  };\n\n  const virtualMetadataNotLikedToModelMock = {\n    target: jest.fn(),\n    name: 'attribute1Mock',\n  };\n\n  const virtualMetadataWithOptionsMock = {\n    target: targetConstructorMock,\n    name: 'virtualMetadataWithOptionsMock',\n    options: virtualOptionsMock,\n  };\n\n  const virtualMetadataWithGetterMock = {\n    target: targetConstructorMock,\n    name: 'virtualMetadataWithGetterMock',\n    options: virtualOptionsMock,\n    getter: jest.fn(),\n  };\n\n  const virtualMetadataWithSetterMock = {\n    target: targetConstructorMock,\n    name: 'virtualMetadataWithSetterMock',\n    options: virtualOptionsMock,\n    setter: jest.fn(),\n  };\n\n  const virtualMetadataWithGetterSetterMock = {\n    target: targetConstructorMock,\n    name: 'virtualMetadataWithGetterSetterMock',\n    options: virtualOptionsMock,\n    getter: jest.fn(),\n    setter: jest.fn(),\n  };\n\n  beforeEach(() => {\n    schemaMock.virtual = jest.fn(() => ({\n      get: setVirtualGetterFunctionMock,\n      set: setVirtualSetterFunctionMock,\n    }));\n  });\n\n  afterEach(() => {\n    jest.resetAllMocks();\n  });\n\n  describe('Schema virtual definition', () => {\n    it('should not define any virtuals if no virtual definitions are stored', () => {\n      TypeMetadataStorage['virtuals'] = [];\n\n      VirtualsFactory.inspect(targetConstructorMock, schemaMock);\n\n      expect(schemaMock.virtual).not.toHaveBeenCalled();\n    });\n\n    it('should not define virtuals if there are no stored virtual definitions linked to the schema model', () => {\n      TypeMetadataStorage['virtuals'] = [virtualMetadataNotLikedToModelMock];\n\n      VirtualsFactory.inspect(targetConstructorMock, schemaMock);\n\n      expect(schemaMock.virtual).not.toHaveBeenCalled();\n    });\n\n    it('should define virtuals for each stored virtual metadata linked to the schema model', () => {\n      TypeMetadataStorage['virtuals'] = [\n        virtualMetadataWithOnlyRequiredAttributesMock,\n        virtualMetadataNotLikedToModelMock,\n        virtualMetadataWithOptionsMock,\n      ];\n\n      VirtualsFactory.inspect(targetConstructorMock, schemaMock);\n\n      expect(schemaMock.virtual['mock'].calls).toEqual([\n        [virtualMetadataWithOnlyRequiredAttributesMock.name, undefined],\n        [\n          virtualMetadataWithOptionsMock.name,\n          virtualMetadataWithOptionsMock.options,\n        ],\n      ]);\n    });\n  });\n\n  describe('Schema virtual getter/setter definitions', () => {\n    it('should not call the getter/setter methods if no getter/setter is defined in the stored virtual metadata linked to the schema model', () => {\n      TypeMetadataStorage['virtuals'] = [\n        virtualMetadataWithOptionsMock,\n      ] as VirtualMetadataInterface[];\n\n      VirtualsFactory.inspect(targetConstructorMock, schemaMock);\n\n      expect(setVirtualGetterFunctionMock).not.toHaveBeenCalled();\n      expect(setVirtualSetterFunctionMock).not.toHaveBeenCalled();\n    });\n\n    it('should invoke the getter/setter methods for each stored virtual metadata with defined getter/setter linked to the schema model', () => {\n      TypeMetadataStorage['virtuals'] = [\n        virtualMetadataWithOptionsMock,\n        virtualMetadataWithGetterMock,\n        virtualMetadataWithSetterMock,\n        virtualMetadataWithGetterSetterMock,\n      ] as VirtualMetadataInterface[];\n\n      VirtualsFactory.inspect(targetConstructorMock, schemaMock);\n\n      expect(setVirtualGetterFunctionMock.mock.calls).toEqual([\n        [virtualMetadataWithGetterMock.getter],\n        [virtualMetadataWithGetterSetterMock.getter],\n      ]);\n      expect(setVirtualSetterFunctionMock.mock.calls).toEqual([\n        [virtualMetadataWithSetterMock.setter],\n        [virtualMetadataWithGetterSetterMock.setter],\n      ]);\n    });\n  });\n});\n"
  },
  {
    "path": "tests/jest-e2e.json",
    "content": "{\n  \"moduleFileExtensions\": [\"js\", \"json\", \"ts\"],\n  \"rootDir\": \".\",\n  \"testEnvironment\": \"node\",\n  \"testRegex\": \".spec.ts$\",\n  \"transform\": {\n    \"^.+\\\\.(t|j)s$\": \"ts-jest\"\n  }\n}\n"
  },
  {
    "path": "tests/src/app.module.ts",
    "content": "import { Module } from '@nestjs/common';\nimport { MongooseModule } from '../../lib';\nimport { CatsModule } from './cats/cats.module';\nimport { CatModule } from './cats/cat.module';\n\n@Module({\n  imports: [\n    MongooseModule.forRoot('mongodb://localhost:27017/test'),\n    CatsModule,\n    CatModule,\n  ],\n})\nexport class AppModule {}\n"
  },
  {
    "path": "tests/src/cats/cat.controller.ts",
    "content": "import { Controller, Get, Param } from '@nestjs/common';\nimport { CatService } from './cat.service';\nimport { Cat } from './schemas/cat.schema';\n\n@Controller('cat')\nexport class CatController {\n  constructor(private readonly catService: CatService) {}\n\n  @Get(':id')\n  async findOne(@Param('id') id: string): Promise<Cat | null> {\n    return this.catService.findOne(id);\n  }\n}\n"
  },
  {
    "path": "tests/src/cats/cat.module.ts",
    "content": "import { Module } from '@nestjs/common';\nimport { MongooseModule } from '../../../lib';\nimport { Cat, CatSchema } from './schemas/cat.schema';\nimport { CatController } from './cat.controller';\nimport { CatService } from './cat.service';\n\n@Module({\n  imports: [MongooseModule.forFeature([{ name: Cat.name, schema: CatSchema }])],\n  controllers: [CatController],\n  providers: [CatService],\n})\nexport class CatModule {}\n"
  },
  {
    "path": "tests/src/cats/cat.service.ts",
    "content": "import { Injectable } from '@nestjs/common';\nimport { Model } from 'mongoose';\nimport { InjectModel } from '../../../lib';\nimport { Cat } from './schemas/cat.schema';\n\n@Injectable()\nexport class CatService {\n  constructor(@InjectModel(Cat.name) private readonly catModel: Model<Cat>) {}\n\n  async findOne(id: string): Promise<Cat | null> {\n    return this.catModel.findById(id).populate('kitten').exec();\n  }\n}\n"
  },
  {
    "path": "tests/src/cats/cats.controller.ts",
    "content": "import { Body, Controller, Get, Post } from '@nestjs/common';\nimport { CatsService } from './cats.service';\nimport { CreateCatDto } from './dto/create-cat.dto';\nimport { Cat } from './schemas/cat.schema';\n\n@Controller('cats')\nexport class CatsController {\n  constructor(private readonly catsService: CatsService) {}\n\n  @Post()\n  async create(@Body() createCatDto: CreateCatDto) {\n    return this.catsService.create(createCatDto);\n  }\n\n  @Get()\n  async findAll(): Promise<Cat[]> {\n    return this.catsService.findAll();\n  }\n}\n"
  },
  {
    "path": "tests/src/cats/cats.module.ts",
    "content": "import { Module } from '@nestjs/common';\nimport { MongooseModule } from '../../../lib';\nimport { CatsController } from './cats.controller';\nimport { CatsService } from './cats.service';\nimport { Cat, CatSchema } from './schemas/cat.schema';\n\n@Module({\n  imports: [MongooseModule.forFeature([{ name: Cat.name, schema: CatSchema }])],\n  controllers: [CatsController],\n  providers: [CatsService],\n})\nexport class CatsModule {}\n"
  },
  {
    "path": "tests/src/cats/cats.service.ts",
    "content": "import { Injectable } from '@nestjs/common';\nimport { Model, Types } from 'mongoose';\nimport { InjectModel } from '../../../lib';\nimport { CreateCatDto } from './dto/create-cat.dto';\nimport { Cat } from './schemas/cat.schema';\n\n@Injectable()\nexport class CatsService {\n  constructor(@InjectModel(Cat.name) private readonly catModel: Model<Cat>) {}\n\n  async create(createCatDto: CreateCatDto): Promise<Cat> {\n    const createdCat = new this.catModel({\n      ...createCatDto,\n      kitten: createCatDto.kitten?.map((kitten) => new Types.ObjectId(kitten)),\n    });\n    return createdCat.save();\n  }\n\n  async findAll(): Promise<Cat[]> {\n    return this.catModel.find().exec();\n  }\n}\n"
  },
  {
    "path": "tests/src/cats/dto/create-cat.dto.ts",
    "content": "export class CreateCatDto {\n  readonly name: string;\n  readonly age: number;\n  readonly breed: string;\n  readonly kitten?: string[];\n}\n"
  },
  {
    "path": "tests/src/cats/schemas/cat.schema.ts",
    "content": "import { Document, Types } from 'mongoose';\nimport { Prop, Schema, SchemaFactory } from '../../../../lib';\n\n@Schema()\nexport class Cat extends Document<Types.ObjectId> {\n  @Prop()\n  name: string;\n\n  @Prop()\n  age: number;\n\n  @Prop()\n  breed: string;\n\n  // see https://github.com/nestjs/mongoose/issues/2421\n  @Prop({\n    type: [{ type: Types.ObjectId, ref: Cat.name }],\n    default: [],\n  })\n  kitten: Types.ObjectId[];\n}\n\nexport const CatSchema = SchemaFactory.createForClass(Cat);\n"
  },
  {
    "path": "tests/src/event/dto/create-click-link-event.dto.ts",
    "content": "export class CreateClickLinkEventDto {\n  kind: string;\n  time: Date;\n  url: string;\n}\n"
  },
  {
    "path": "tests/src/event/dto/create-sign-up-event.dto.ts",
    "content": "export class CreateSignUpEventDto {\n  kind: string;\n  time: Date;\n  user: string;\n}\n"
  },
  {
    "path": "tests/src/event/event.controller.ts",
    "content": "import { Body, Controller, Get, Post } from '@nestjs/common';\nimport { CreateClickLinkEventDto } from './dto/create-click-link-event.dto';\nimport { CreateSignUpEventDto } from './dto/create-sign-up-event.dto';\nimport { EventService } from './event.service';\nimport { ClickLinkEvent } from './schemas/click-link-event.schema';\nimport { Event } from './schemas/event.schema';\nimport { SignUpEvent } from './schemas/sign-up-event.schema';\n\n@Controller('event')\nexport class EventController {\n  constructor(private readonly eventService: EventService) {}\n\n  @Post('click-link')\n  async createClickLinkEvent(\n    @Body() dto: CreateClickLinkEventDto,\n  ): Promise<unknown> {\n    return this.eventService.create({\n      ...dto,\n      time: new Date(),\n      kind: ClickLinkEvent.name,\n    });\n  }\n\n  @Post('sign-up')\n  async create(@Body() dto: CreateSignUpEventDto): Promise<unknown> {\n    return this.eventService.create({\n      ...dto,\n      time: new Date(),\n      kind: SignUpEvent.name,\n    });\n  }\n\n  @Get()\n  async findAll(): Promise<Event[]> {\n    return this.eventService.findAll();\n  }\n}\n"
  },
  {
    "path": "tests/src/event/event.module.ts",
    "content": "import { DynamicModule, Module } from '@nestjs/common';\nimport { EventService } from './event.service';\nimport { EventController } from './event.controller';\n\n@Module({})\nexport class EventModule {\n  static forFeature(module: DynamicModule): DynamicModule {\n    return {\n      imports: [module],\n      module: EventModule,\n      controllers: [EventController],\n      providers: [EventService],\n    };\n  }\n}\n"
  },
  {
    "path": "tests/src/event/event.service.ts",
    "content": "import { Injectable } from '@nestjs/common';\nimport { Document, Model } from 'mongoose';\nimport { InjectModel } from '../../../lib';\nimport { CreateClickLinkEventDto } from './dto/create-click-link-event.dto';\nimport { CreateSignUpEventDto } from './dto/create-sign-up-event.dto';\nimport { ClickLinkEvent } from './schemas/click-link-event.schema';\nimport { Event } from './schemas/event.schema';\nimport { SignUpEvent } from './schemas/sign-up-event.schema';\n\n@Injectable()\nexport class EventService {\n  constructor(\n    @InjectModel(Event.name)\n    private readonly eventModel: Model<Event & Document>,\n\n    @InjectModel(ClickLinkEvent.name)\n    private readonly clickEventModel: Model<Event & Document>,\n\n    @InjectModel(SignUpEvent.name)\n    private readonly signUpEventModel: Model<Event & Document>,\n  ) {}\n\n  async create(\n    createDto: CreateClickLinkEventDto | CreateSignUpEventDto,\n  ): Promise<Event> {\n    const createdEvent = new this.eventModel(createDto);\n    return createdEvent.save();\n  }\n\n  async findAll(): Promise<Event[]> {\n    return this.eventModel.find().exec();\n  }\n}\n"
  },
  {
    "path": "tests/src/event/schemas/click-link-event.schema.ts",
    "content": "import { Prop, Schema, SchemaFactory } from '../../../../lib';\nimport { Event } from './event.schema';\n\n@Schema({})\nexport class ClickLinkEvent implements Event {\n  kind: string;\n\n  time: Date;\n\n  @Prop({ type: String, required: true })\n  url: string;\n}\n\nexport const ClieckLinkEventSchema = SchemaFactory.createForClass(\n  ClickLinkEvent,\n);\n"
  },
  {
    "path": "tests/src/event/schemas/event.schema.ts",
    "content": "import { Prop, Schema, SchemaFactory } from '../../../../lib';\nimport { ClickLinkEvent } from './click-link-event.schema';\nimport { SignUpEvent } from './sign-up-event.schema';\n\n@Schema({ discriminatorKey: 'kind' })\nexport class Event {\n  @Prop({\n    type: String,\n    required: true,\n    enum: [ClickLinkEvent.name, SignUpEvent.name],\n  })\n  kind: string;\n\n  @Prop({ type: Date, required: true })\n  time: Date;\n}\n\nexport const EventSchema = SchemaFactory.createForClass(Event);\n"
  },
  {
    "path": "tests/src/event/schemas/sign-up-event.schema.ts",
    "content": "import { Prop, Schema, SchemaFactory } from '../../../../lib';\nimport { Event } from './event.schema';\n\n@Schema({})\nexport class SignUpEvent implements Event {\n  kind: string;\n\n  time: Date;\n\n  @Prop({ type: String, required: true })\n  user: string;\n}\n\nexport const SignUpEventSchema = SchemaFactory.createForClass(SignUpEvent);\n"
  },
  {
    "path": "tests/src/lazy-app.module.ts",
    "content": "import { Module } from '@nestjs/common';\nimport { MongooseModule } from '../../lib';\nimport { CatsModule } from './cats/cats.module';\n\n@Module({\n  imports: [\n    MongooseModule.forRoot('mongodb://localhost:27017/test', {\n      lazyConnection: true,\n    }),\n    CatsModule,\n  ],\n})\nexport class LazyAppModule {}\n"
  },
  {
    "path": "tests/src/main.ts",
    "content": "import { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  await app.listen(3000);\n  console.log(`Application is running on: ${await app.getUrl()}`);\n}\nbootstrap();\n"
  },
  {
    "path": "tsconfig.build.json",
    "content": "{\n  \"extends\": \"./tsconfig.json\",\n  \"compilerOptions\": {\n    \"outDir\": \"./dist\",\n    \"rootDir\": \"./lib\"\n  },\n  \"include\": [\"lib/**/*\"],\n  \"exclude\": [\"node_modules\", \"tests\", \"dist\", \"**/*spec.ts\"]\n}\n"
  },
  {
    "path": "tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"module\": \"commonjs\",\n    \"declaration\": true,\n    \"noImplicitAny\": false,\n    \"removeComments\": true,\n    \"noLib\": false,\n    \"emitDecoratorMetadata\": true,\n    \"experimentalDecorators\": true,\n    \"target\": \"ES2021\",\n    \"sourceMap\": true,\n    \"skipLibCheck\": true,\n    \"strict\": true,\n    \"strictPropertyInitialization\": false\n  }\n}\n"
  }
]