{"id":18926841,"url":"https://github.com/ladjs/mongoose-unique-validator","last_synced_at":"2025-07-19T02:02:11.586Z","repository":{"id":63442057,"uuid":"567439130","full_name":"ladjs/mongoose-unique-validator","owner":"ladjs","description":"Mongoose plugin which adds pre-save validation for unique fields within a Mongoose schema. This makes error handling much easier, since you will get a Mongoose validation error when you attempt to violate a unique constraint, rather than an E11000 error from MongoDB.  Fork of the original unmaintained package.","archived":false,"fork":false,"pushed_at":"2022-11-28T07:27:58.000Z","size":204,"stargazers_count":0,"open_issues_count":0,"forks_count":1,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-06-27T22:49:39.266Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ladjs.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2022-11-17T19:48:46.000Z","updated_at":"2022-11-17T19:49:10.000Z","dependencies_parsed_at":"2023-01-22T07:18:24.743Z","dependency_job_id":null,"html_url":"https://github.com/ladjs/mongoose-unique-validator","commit_stats":null,"previous_names":[],"tags_count":2,"template":false,"template_full_name":null,"purl":"pkg:github/ladjs/mongoose-unique-validator","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ladjs%2Fmongoose-unique-validator","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ladjs%2Fmongoose-unique-validator/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ladjs%2Fmongoose-unique-validator/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ladjs%2Fmongoose-unique-validator/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ladjs","download_url":"https://codeload.github.com/ladjs/mongoose-unique-validator/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ladjs%2Fmongoose-unique-validator/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":265871782,"owners_count":23842066,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-08T11:17:19.627Z","updated_at":"2025-07-19T02:02:10.892Z","avatar_url":"https://github.com/ladjs.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# @ladjs/mongoose-unique-validator\n\n[![build status](https://github.com/ladjs/mongoose-unique-validator/actions/workflows/ci.yml/badge.svg)](https://github.com/ladjs/mongoose-unique-validator/actions/workflows/ci.yml)\n[![code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/sindresorhus/xo)\n[![styled with prettier](https://img.shields.io/badge/styled_with-prettier-ff69b4.svg)](https://github.com/prettier/prettier)\n[![made with lass](https://img.shields.io/badge/made_with-lass-95CC28.svg)](https://lass.js.org)\n[![license](https://img.shields.io/github/license/ladjs/mongoose-unique-validator.svg)]()\n\n\u003e Mongoose plugin which adds pre-save validation for unique fields within a Mongoose schema. This makes error handling much easier, since you will get a Mongoose validation error when you attempt to violate a [unique constraint](http://mongoosejs.com/docs/api.html#schematype_SchemaType-unique), rather than an E11000 error from MongoDB.  Fork of the [original unmaintained package](https://github.com/mongoose-unique-validator/mongoose-unique-validator).\n\n\u003e **NOTE:** As of v5.0.0+ if the only unique index is `_id`, then E11000 will be thrown by default.  This prevents an unnecessary call to `countDocuments` and is a major optimization.\n\n\n## Table of Contents\n\n* [Install](#install)\n* [Usage](#usage)\n* [Example](#example)\n* [Find + Updates](#find--updates)\n* [Custom Error Types](#custom-error-types)\n* [Custom Error Messages](#custom-error-messages)\n* [Case Insensitive](#case-insensitive)\n* [Additional Conditions](#additional-conditions)\n* [Caveats](#caveats)\n* [Contributors](#contributors)\n* [License](#license)\n\n\n## Install\n\n[npm][]:\n\n```sh\nnpm install @ladjs/mongoose-unique-validator\n```\n\n\n## Usage\n\n```js\nconst mongoose = require('mongoose');\nconst uniqueValidator = require('@ladjs/mongoose-unique-validator');\n\nconst mySchema = mongoose.Schema({\n  // TODO: put your schema definition here\n});\n\n// NOTE: this should come after any indexes are added to your schema (incl from other plugins)\nmySchema.plugin(uniqueValidator);\n```\n\n\n## Example\n\nLet's say you have a user schema. You can easily add validation for the unique constraints in this schema by applying the `uniqueValidator` plugin to your user schema:\n\n```js\nconst mongoose = require('mongoose');\nconst uniqueValidator = require('@ladjs/mongoose-unique-validator');\n\n// Define your schema as normal.\nconst userSchema = mongoose.Schema({\n  username: { type: String, required: true, unique: true },\n  email: { type: String, index: true, unique: true, required: true },\n  password: { type: String, required: true }\n});\n\n// Apply the uniqueValidator plugin to userSchema.\nuserSchema.plugin(uniqueValidator);\n```\n\nNow when you try to save a user, the unique validator will check for duplicate database entries and report them just like any other validation error:\n\n```js\nconst user = new User({ username: 'JohnSmith', email: 'john.smith@gmail.com', password: 'j0hnNYb0i' });\nawait user.save();\n```\n\n```js\n{\n  message: 'Validation failed',\n  name: 'ValidationError',\n  errors: {\n    username: {\n      message: 'Error, expected `username` to be unique. Value: `JohnSmith`',\n      name: 'ValidatorError',\n      kind: 'unique',\n      path: 'username',\n      value: 'JohnSmith'\n    }\n  }\n}\n```\n\n\n## Find + Updates\n\nWhen using `findOneAndUpdate` and related methods, mongoose doesn't automatically run validation. To trigger this, you need to pass a configuration object. For technical reasons, this plugin requires that you also set the context option to `query`.\n\n```js\n{ runValidators: true, context: 'query' }\n```\n\nA full example:\n\n```js\nawait User.findOneAndUpdate(\n  { email: 'old-email@example.com' },\n  { email: 'new-email@example.com' },\n  { runValidators: true, context: 'query' }\n);\n```\n\n\n## Custom Error Types\n\nYou can pass through a custom error type as part of the optional `options` argument:\n\n```js\nuserSchema.plugin(uniqueValidator, { type: 'mongoose-unique-validator' });\n```\n\nAfter running the above example the output will be:\n\n```js\n{\n  message: 'Validation failed',\n  name: 'ValidationError',\n  errors: {\n    username: {\n      message: 'Error, expected `username` to be unique. Value: `JohnSmith`',\n      name: 'ValidatorError',\n      kind: 'mongoose-unique-validator',\n      path: 'username',\n      value: 'JohnSmith'\n    }\n  }\n}\n```\n\nYou can also specify a default custom error type by overriding the plugin `defaults.type` variable:\n\n```js\nuniqueValidator.defaults.type = 'mongoose-unique-validator'\n```\n\n\n## Custom Error Messages\n\nYou can pass through a custom error message as part of the optional `options` argument:\n\n```js\nuserSchema.plugin(uniqueValidator, { message: 'Error, expected {PATH} to be unique.' });\n```\n\nYou have access to all of the standard Mongoose error message templating:\n\n* `{PATH}`\n* `{VALUE}`\n* `{TYPE}`\n\nYou can also specify a default custom error message by overriding the plugin `defaults.message` variable:\n\n```js\nuniqueValidator.defaults.message = 'Error, expected {PATH} to be unique.'\n```\n\n\n## Case Insensitive\n\nFor case-insensitive matches, include the `uniqueCaseInsensitive` option in your schema. Queries will treat `john.smith@gmail.com` and `John.Smith@gmail.com` as duplicates.\n\n```js\nconst userSchema = mongoose.Schema({\n  username: { type: String, required: true, unique: true },\n  email: { type: String, index: true, unique: true, required: true, uniqueCaseInsensitive: true },\n  password: { type: String, required: true }\n});\n```\n\n\n## Additional Conditions\n\nFor additional unique-constraint conditions (ex: only enforce unique constraint on non soft-deleted records), the MongoDB option `partialFilterExpression` can be used.\n\nNote: the option `index` must be passed as an object containing `unique: true`, or else `partialFilterExpression` will be ignored.\n\n```js\nconst userSchema = mongoose.Schema({\n  username: { type: String, required: true, unique: true },\n  email: {\n    type: String,\n    required: true,\n    index: {\n      unique: true,\n      partialFilterExpression: { deleted: false }\n    }\n  },\n  password: { type: String, required: true }\n});\n```\n\n\n## Caveats\n\nBecause we rely on async operations to verify whether a document exists in the database, it's possible for two queries to execute at the same time, both get 0 back, and then both insert into MongoDB.\n\nOutside of automatically locking the collection or forcing a single connection, there's no real solution.\n\nFor most of our users this won't be a problem, but is an edge case to be aware of.\n\n\n## Contributors\n\n| Name            |\n| --------------- |\n| **Mike Botsko** |\n\n\n## License\n\n[MIT](https://opensource.org/licenses/MIT) © [Blake Haswell](http://blakehaswell.com/)\n\n\n##\n\n[npm]: https://www.npmjs.com/\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fladjs%2Fmongoose-unique-validator","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fladjs%2Fmongoose-unique-validator","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fladjs%2Fmongoose-unique-validator/lists"}