Skip to content

Commit

Permalink
feat(db-mongodb): allow to customize mongoose schema options with `co…
Browse files Browse the repository at this point in the history
…llectionsSchemaOptions` (#9885)

Adds the ability to pass additional schema options for collections with:
```ts
mongooseAdapter({
  collectionsSchemaOptions: {
    posts: {
      strict: false,
    },
  },
})
``` 

This changes relates to these:

-   #4533
-   #4534

It is a proposal to set custom schema options for mongoose driver. 

I understand this got introduced into `main` v2 after `beta` branch was
created so this feature got lost.

- [x] I have read and understand the
[CONTRIBUTING.md](https://github.com/payloadcms/payload/blob/main/CONTRIBUTING.md)
document in this repository.

<!--

Thank you for the PR! Please go through the checklist below and make
sure you've completed all the steps.

Please review the
[CONTRIBUTING.md](https://github.com/payloadcms/payload/blob/main/CONTRIBUTING.md)
document in this repository if you haven't already.

The following items will ensure that your PR is handled as smoothly as
possible:

- PR Title must follow conventional commits format. For example, `feat:
my new feature`, `fix(plugin-seo): my fix`.
- Minimal description explained as if explained to someone not
immediately familiar with the code.
- Provide before/after screenshots or code diffs if applicable.
- Link any related issues/discussions from GitHub or Discord.
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Fixes #

-->

---------

Co-authored-by: Sasha <64744993+r1tsuu@users.noreply.github.com>
  • Loading branch information
javierlinked and r1tsuu authored Dec 18, 2024
1 parent b8de401 commit 198763a
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 11 deletions.
17 changes: 9 additions & 8 deletions docs/database/mongodb.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,15 @@ export default buildConfig({

## Options

| Option | Description |
| -------------------- | ----------- |
| `autoPluralization` | Tell Mongoose to auto-pluralize any collection names if it encounters any singular words used as collection `slug`s. |
| `connectOptions` | Customize MongoDB connection options. Payload will connect to your MongoDB database using default options which you can override and extend to include all the [options](https://mongoosejs.com/docs/connections.html#options) available to mongoose. |
| `disableIndexHints` | Set to true to disable hinting to MongoDB to use 'id' as index. This is currently done when counting documents for pagination, as it increases the speed of the count function used in that query. Disabling this optimization might fix some problems with AWS DocumentDB. Defaults to false |
| `migrationDir` | Customize the directory that migrations are stored. |
| `transactionOptions` | An object with configuration properties used in [transactions](https://www.mongodb.com/docs/manual/core/transactions/) or `false` which will disable the use of transactions. |
| `collation` | Enable language-specific string comparison with customizable options. Available on MongoDB 3.4+. Defaults locale to "en". Example: `{ strength: 3 }`. For a full list of collation options and their definitions, see the [MongoDB documentation](https://www.mongodb.com/docs/manual/reference/collation/). |
| Option | Description |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `autoPluralization` | Tell Mongoose to auto-pluralize any collection names if it encounters any singular words used as collection `slug`s. |
| `connectOptions` | Customize MongoDB connection options. Payload will connect to your MongoDB database using default options which you can override and extend to include all the [options](https://mongoosejs.com/docs/connections.html#options) available to mongoose. |
| `collectionsSchemaOptions` | Customize Mongoose schema options for collections. |
| `disableIndexHints` | Set to true to disable hinting to MongoDB to use 'id' as index. This is currently done when counting documents for pagination, as it increases the speed of the count function used in that query. Disabling this optimization might fix some problems with AWS DocumentDB. Defaults to false |
| `migrationDir` | Customize the directory that migrations are stored. |
| `transactionOptions` | An object with configuration properties used in [transactions](https://www.mongodb.com/docs/manual/core/transactions/) or `false` which will disable the use of transactions. |
| `collation` | Enable language-specific string comparison with customizable options. Available on MongoDB 3.4+. Defaults locale to "en". Example: `{ strength: 3 }`. For a full list of collation options and their definitions, see the [MongoDB documentation](https://www.mongodb.com/docs/manual/reference/collation/). |

## Access to Mongoose models

Expand Down
15 changes: 13 additions & 2 deletions packages/db-mongodb/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
import type { CollationOptions, TransactionOptions } from 'mongodb'
import type { MongoMemoryReplSet } from 'mongodb-memory-server'
import type { ClientSession, Connection, ConnectOptions, QueryOptions } from 'mongoose'
import type {
ClientSession,
Connection,
ConnectOptions,
QueryOptions,
SchemaOptions,
} from 'mongoose'
import type {
BaseDatabaseAdapter,
CollectionSlug,
DatabaseAdapterObj,
Payload,
TypeWithID,
Expand Down Expand Up @@ -79,12 +86,13 @@ export interface Args {
* Defaults to disabled.
*/
collation?: Omit<CollationOptions, 'locale'>
collectionsSchemaOptions?: Partial<Record<CollectionSlug, SchemaOptions>>

/** Extra configuration options */
connectOptions?: {
/** Set false to disable $facet aggregation in non-supporting databases, Defaults to true */
useFacet?: boolean
} & ConnectOptions

/** Set to true to disable hinting to MongoDB to use 'id' as index. This is currently done when counting documents for pagination. Disabling this optimization might fix some problems with AWS DocumentDB. Defaults to false */
disableIndexHints?: boolean
/**
Expand All @@ -103,6 +111,7 @@ export interface Args {
up: (args: MigrateUpArgs) => Promise<void>
}[]
transactionOptions?: false | TransactionOptions

/** The URL to connect to MongoDB or false to start payload and prevent connecting */
url: false | string
}
Expand Down Expand Up @@ -163,6 +172,7 @@ declare module 'payload' {

export function mongooseAdapter({
autoPluralization = true,
collectionsSchemaOptions = {},
connectOptions,
disableIndexHints = false,
ensureIndexes,
Expand Down Expand Up @@ -194,6 +204,7 @@ export function mongooseAdapter({
versions: {},
// DatabaseAdapter
beginTransaction: transactionOptions === false ? defaultBeginTransaction() : beginTransaction,
collectionsSchemaOptions,
commitTransaction,
connect,
count,
Expand Down
5 changes: 4 additions & 1 deletion packages/db-mongodb/src/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ import { getDBName } from './utilities/getDBName.js'

export const init: Init = function init(this: MongooseAdapter) {
this.payload.config.collections.forEach((collection: SanitizedCollectionConfig) => {
const schema = buildCollectionSchema(collection, this.payload)
const schemaOptions = this.collectionsSchemaOptions[collection.slug]

const schema = buildCollectionSchema(collection, this.payload, schemaOptions)

if (collection.versions) {
const versionModelName = getDBName({ config: collection, versions: true })
Expand All @@ -32,6 +34,7 @@ export const init: Init = function init(this: MongooseAdapter) {
minimize: false,
timestamps: false,
},
...schemaOptions,
})

versionSchema.plugin<any, PaginateOptions>(paginate, { useEstimatedCount: true }).plugin(
Expand Down

0 comments on commit 198763a

Please sign in to comment.