Open In App

Mongoose SchemaType.prototype.unique() API

Improve
Improve
Like Article
Like
Save
Share
Report

Mongoose is a MongoDB object modeling and handling for a node.js environment. Mongoose SchemaType unique property allows us to create unique indices on mongoose paths that we do not want to get duplicated in the documents. Let’s understand more about this with some examples.

Creating node application And Installing Mongoose:

Step 1: Create a node application using the following command:

mkdir folder_name
cd folder_name
npm init -y
touch main.js

Step 2: After creating the ReactJS application, Install the required module using the following command:

npm install mongoose

Project Structure: It will look like the following.

 

Example 1: In this example, we will create a unique index on a schema path, email, so that the user won’t be able to save documents with the same emails.

Filename: main.js

Javascript




const mongoose = require('mongoose')
  
// Database connection
    dbName: 'event_db',
    useNewUrlParser: true,
    useUnifiedTopology: true
}, err => err ? console.log(err) : console.log('Connected to database'));
  
const personSchema = new mongoose.Schema({
    name: {
        type: String,
    },
    email: {
        type: String,
        unique: true
    }
}, { strict: true });
  
const Person = mongoose.model('Person', personSchema);
const person1 = new Person({ name: 'John'
    email: 'john@test.com' });
const person2 = new Person({ name: 'Doe'
    email: 'john@test.com' });
  
(async function () {
    await person1.save();
    await person2.save(function (err) {
        console.log(err)
    });
  
    const persons = await Person.find()
    console.log(persons)
})()


Step to Run Application: Run the application using the following command from the root directory of the project:

node main.js

Output:

 

Example 2: In this example, we will create a unique index on a schema path, “name”, so that the user won’t be able to save documents with the same names.

Filename: main.js

Javascript




const mongoose = require('mongoose')
  
// Database connection
    dbName: 'event_db',
    useNewUrlParser: true,
    useUnifiedTopology: true
}, err => err ? console.log(err) : 
    console.log('Connected to database'));
  
const personSchema = new mongoose.Schema({
    name: {
        type: String,
        unique: true
    },
    email: {
        type: String,
    }
}, { strict: true });
  
const Person = mongoose.model('Person', personSchema);
const person1 = new Person({ name: 'John'
    email: 'john@test.com' });
const person2 = new Person({ name: 'John'
    email: 'doe@test.com' });
  
(async function () {
    await person1.save();
    await person2.save(function (err) {
        console.log(err)
    });
  
    const persons = await Person.find()
    console.log(persons)
})()


Step to Run Application: Run the application using the following command from the root directory of the project:

node main.js

Output:

 

Reference: https://mongoosejs.com/docs/api/schematype.html#schematype_SchemaType-unique



Last Updated : 02 Nov, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads