npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

mongoose-unique-validator

v6.0.0

Published

mongoose-unique-validator is a plugin which adds pre-save validation for unique fields within a Mongoose schema.

Readme

mongoose-unique-validator

npm version CI License: MIT

mongoose-unique-validator is a 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.

Table of Contents

Installation

npm install mongoose-unique-validator
# or
yarn add mongoose-unique-validator
# or
pnpm add mongoose-unique-validator

Quick Start

Apply the plugin to your schema:

import mongoose from 'mongoose'
import uniqueValidator from 'mongoose-unique-validator'

const userSchema = mongoose.Schema({
  username: { type: String, required: true, unique: true },
  email: { type: String, index: true, unique: true, required: true },
  password: { type: String, required: true }
})

userSchema.plugin(uniqueValidator)

Now when you try to save a duplicate, the error is reported as a standard Mongoose ValidationError:

try {
  const user = new User({
    username: 'JohnSmith',
    email: '[email protected]',
    password: 'j0hnNYb0i'
  })

  await user.save()
} catch (err) {
  // err.name === 'ValidationError'
}
{
    message: 'Validation failed',
    name: 'ValidationError',
    errors: {
        username: {
            message: 'Error, expected `username` to be unique. Value: `JohnSmith`',
            name: 'ValidatorError',
            kind: 'unique',
            path: 'username',
            value: 'JohnSmith'
        }
    }
}

Find + Updates

findOneAndUpdate and related methods don't run validation by default. Pass { runValidators: true, context: 'query' } to enable it:

User.findOneAndUpdate(
  { email: '[email protected]' },
  { email: '[email protected]' },
  { runValidators: true, context: 'query' },
  function (err) {
    // ...
  }
)

context: 'query' is required — without it this plugin cannot access the update values.

Custom Error Types

Pass a type option to control the kind field on the ValidatorError:

userSchema.plugin(uniqueValidator, { type: 'mongoose-unique-validator' })
{
    errors: {
        username: {
            kind: 'mongoose-unique-validator',  // <--
            ...
        }
    }
}

You can also set this globally — see Global Defaults.

Custom Error Messages

Pass a message option to customize the error message. The following template variables are available:

  • {PATH} — the field name
  • {VALUE} — the duplicate value
  • {TYPE} — the error kind
userSchema.plugin(uniqueValidator, {
  message: 'Error, expected {PATH} to be unique.'
})

You can also set this globally — see Global Defaults.

Custom Error Codes

Pass a code option to attach a numeric or string code to each ValidatorError:

userSchema.plugin(uniqueValidator, { code: 11000 })

The code is available under properties.code:

{
    errors: {
        username: {
            properties: {
                code: 11000  // <--
            },
            ...
        }
    }
}

You can also set this globally — see Global Defaults.

Global Defaults

Instead of passing options to every schema.plugin(uniqueValidator, ...) call, set defaults once at startup. Per-schema options always take precedence.

import uniqueValidator from 'mongoose-unique-validator'

uniqueValidator.defaults.type = 'mongoose-unique-validator'
uniqueValidator.defaults.message = 'Error, expected {PATH} to be unique.'
uniqueValidator.defaults.code = 11000

Case Insensitive

Add uniqueCaseInsensitive: true to a field to treat values as case-insensitively equal. For example, [email protected] and [email protected] will be considered duplicates.

const userSchema = mongoose.Schema({
  username: { type: String, required: true, unique: true },
  email: {
    type: String,
    index: true,
    unique: true,
    required: true,
    uniqueCaseInsensitive: true
  },
  password: { type: String, required: true }
})

Additional Conditions

Use MongoDB's partialFilterExpression to scope the uniqueness constraint. For example, to only enforce uniqueness among non-deleted records:

const userSchema = mongoose.Schema({
  username: { type: String, required: true, unique: true },
  email: {
    type: String,
    required: true,
    index: {
      unique: true,
      partialFilterExpression: { deleted: false }
    }
  },
  password: { type: String, required: true }
})

Note: index must be an object containing unique: true — shorthand like index: true, unique: true will cause partialFilterExpression to be ignored.

Caveats

This plugin validates uniqueness by querying the database before save. Because two saves can run concurrently, both can read a count of zero and then both proceed to insert — resulting in a duplicate that MongoDB's unique index will reject with a raw E11000 error rather than a Mongoose ValidationError.

This plugin is therefore a UX layer, not a correctness guarantee. The unique index on the MongoDB collection remains the true enforcement mechanism and should always be kept in place. For most applications the race window is negligible, but in high-concurrency write scenarios be aware that the E11000 path is still reachable.