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