Thursday, 8 June 2017

mongoose Compound index in one-to-many relationship

Given a One-to-Many relationship Group -> has-many Roles, can I build a unique index based on parent and child fields

group.model

/**
 * Group Schema
 */
const GroupSchema = new Schema({
  name: { type: String, index: { unique: true, required: true, dropDups: true } },
  description: { type: String, required: false },
  createdAt: { ype: Date, default: Date.now }
});

role.model

/**
 * Role Schema
 */
const Role = new Schema({
  groupName: { type: String, ref: 'Group.name'},
  name: { type: String, required: true, dropDups: true },
  description: { type: String, required: false },
  createdAt: { type: Date, default: Date.now }
});

Role.index({ groupName: 1, name: -1 }, { unique: true })

I would like to have unique role names but only within a group



via erwin

No comments:

Post a Comment