user3310334
user3310334

Reputation:

mongoose make sure document is unique

I know I can add unique fields in schemas, and using some library (e.g. mongoose-unique-validator) I can validate that no two documents have the same value for that field.

However, how can I ensure that the combination of all fields is unique?

E.g. this should be allowed:

new Model({name: 'foo', prop: 'bar'})
new Model({name: 'qux', prop: 'bar'})
new Model({name: 'foo', prop: 'qux'})

but this should not

new Model({name: 'foo', prop: 'bar'})
new Model({name: 'qux', prop: 'baz'})
new Model({name: 'foo', prop: 'bar'})

Upvotes: 1

Views: 672

Answers (2)

Ashh
Ashh

Reputation: 46441

I think you need to set compound index... You can try this

schema.index({ "name": 1, "prop": 1 }, { unique: true, sparse: true })

Upvotes: 0

cymruu
cymruu

Reputation: 3008

I don't think there is other option than checking if any document exists for each property in checked object.

async function hasAllProperitiesUnique(doc, cb){
    var queries = [];
    for (const v in doc) {
        queries.push(Model.count({v:doc[v]}));
    }
    return Promise.all(queries).then(res=>res.reduce((p,c)=>p+c,0))===0;
}

Upvotes: 1

Related Questions