Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a field 'unique' ONLY within a user (mongoose)

I have a standard mongoose User Scheme, and a 'Uniform' scheme that holds dress items in the following way:

mongoose.Schema({
    user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
    items: { type: [String], unique: true }
})

Thing is, I want the items in the 'items' array to be unique only in the scope of the user. Meaning that I don't want a user to have serval uniforms with the same item. But I don't have any problem with other users having the same items as my user.

The current scheme prevents ANY uniform to have the same values inside 'items', I want it to be just within the scope of the user. Can that even be done?

(In ruby on rails, the line that creates this behavior is: validates_uniqueness_of :items, scope: [:user])

like image 401
dneumark Avatar asked Nov 05 '25 05:11

dneumark


1 Answers

If User and Uniform are different schemas (different collections) then having uniqueness achieved between keys of different collections cannot be done in mongodb.

We can have uniqueness achieved by combining different keys of a same collection using Compound Index

like image 59
Clement Amarnath Avatar answered Nov 06 '25 21:11

Clement Amarnath



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!