mehdi parastar
mehdi parastar

Reputation: 827

How to define a unique field in mongoose schema?

My Schema is like below:

const schema = new mongoose.Schema({
    a: {
        b: { type: String, unique: true },
        c: { type: String }
    },
    aa: {
        bb: [{
            cc: { type: String, unique: true },
            dd: { type: String }
        }]
    }
})

now I want to 'b' and 'cc' fields be unique. how can i do this?

I added this code at the end of the top code, but the schema allows duplicate values.

schema.index({'a.b':1}, {unique:true})
schema.index({'aa.bb.cc':1, {unique:true})

Do you have any idea to solve this problem?

Upvotes: 0

Views: 5061

Answers (2)

cmoshe
cmoshe

Reputation: 369

try adding dropDups as shown below.

const schema = new mongoose.Schema({
a: {
    b: { type: String, unique: true, dropDups: true },
    c: { type: String }
},
aa: {
    bb: [{
        cc: { type: String, unique: true, dropDups: true },
        dd: { type: String }
    }]
}

})

if it doesn't work try: -

const schema = new mongoose.Schema({
a: {
    b: { type: String, index: { unique: true, dropDups: true } },
    c: { type: String }
},
aa: {
    bb: [{
        cc: { type: String, index: { unique: true, dropDups: true } },
        dd: { type: String }
    }]
}

})

Upvotes: 1

Joe
Joe

Reputation: 28326

The answer here depends on exactly what you mean by "I want to 'b' and 'cc' fields be unique."

Mongoose implements the unique constraint by creating a MongoDB index on that field with the unique:true option.

MongoDB enforces the unique option by not allowing the same value to be stored twice in the index.

When a document is written to MongoDB, it extracts the field values from the document that are required by the index, deduplicates the list, and then stores the values in the index with a pointer to the document.

This means that only 1 document may contain a specific value, but that document may contain that value many times.

For example:

If there is an index on {i:1}, these sample documents would have the following entries in the index:

Document Index entries
{i:1} 1=>
{i:[2,3,4] 2=>
3=>
4=>
{i:[5,6,5,6,5]} 5=>
6=>
{i:[2,6]} 2=>
6=>

If the index were unique, and the documents were inserted in exactly that order, the first 3 documents would be perfectly acceptible, and the last would result in a duplicate key error.

Upvotes: 1

Related Questions