Data validation for a unique value within another collection

Hi. A noob question here:
I have a collection of Hotels and a collection of Rooms. Let’s say Hotel California has rooms 1, 2 and 3 and Hotel Minnesota has rooms 1, 2, 3, 4. Here’s a schema:

const roomSchema = new mongoose.Schema({
    number: {
        type: String,
        required: true,
        // unique: true, <-- this will check for unique within all existing rooms
        // validate: ...
    },
    hotel: {
        type: mongoose.Schema.ObjectId,
        ref: 'Hotel'
    }
});

So I’m wondering if it’s possible to validate for a unique number within the “hotel collection” when a room is created. Rooms collection can have multiple rooms 1, but Hotel California or Hotel Minnesota can’t have two rooms 1.

Thanks.

A unique compound index such as

hotel : 1 , number : 1 

should prevent allow the creation of

{ hotel : "california" , room : "666" }
{ hotel : "minnesota" , room : "666" } 

while preventing multiple instances of the above.

1 Like

It works! :+1:

roomSchema.index( { hotel: 1, room: 1 }, { unique: true } )
1 Like