tommybananas
tommybananas

Reputation: 5736

Mongoose JS subdocument unique validation

I'm building an application that uses mobile device UID's as one of the means to authenticate sessions per parent model. My intention being a user can be authenticated to multiple parents but only have one session entry in the database per parent.

ParentSchema {
  sessions: [{
   device_uid: { type: String, unique: true }
  }]
}

Session is it's own schema object (written inline for simplicity sake).

My question is: If I put the unique validation on the device_uid, is the context of the validation the subdocuments for IT'S parent or ALL session subdocuments for ALL parents?

Upvotes: 4

Views: 1483

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312129

A unique index on device_uid within the sub-doc of the sessions array ensures that no two documents can have a sessions array element with the same device_uid. It does, however, still allow two elements within the same document to have the same device_uid.

Upvotes: 2

Related Questions