-1

I have a Parent Document and a Child document where I need the children fields to be unique on the parent only. There can be a million John Smiths, but I need there to only be one John Smith for each Parent

// Parent
const mongoose = require('mongoose')
const { Schema } = mongoose

const ParentSchema = new Schema({
  // ...
  children: [ChildSchema] // embeds many
}, {
  timestamps: {
    // ...
  }
})

ParentSchema.index({
  'children.firstName': 1,
  'children.lastName': 1
}, {
  unique: true,
  sparse: true
})
// Child
const ChildSchema = new Schema({
  firstName: { type: String },
  lastName: { type: String }
}, {
  timestamps: {
    // ...
  }
})
alilland
  • 1,370
  • 1
  • 16
  • 32
  • So you need the combination of `Child.firstName`,`Child.lastName`, and `Parent._id` to be unique? – Joe Mar 06 '20 at 18:23
  • @Joe yes, exactly – alilland Mar 06 '20 at 18:25
  • Just to play devil's advocate, What happens if someone has 5 sons and gives them all the same name? like [George](https://en.wikipedia.org/wiki/George_Foreman) – Joe Mar 06 '20 at 18:25
  • @Joe the example given was just to simplify another use case, its actually for a pricing diagram – alilland Mar 06 '20 at 18:26
  • I was just trying to be funny (and aparently failing - I'll stick to the day job) – Joe Mar 06 '20 at 18:27
  • Check out https://stackoverflow.com/a/12574045/2282634 – Joe Mar 06 '20 at 18:27
  • @Joe all good =] -- tried what that post referenced, it works on parent documents but unfortunately not when applying to children – alilland Mar 06 '20 at 18:28
  • You would apply that index to the parent, like `ParentSchema.index({ "children.firstName": 1, "children.lastName":1, "_id":1 },{unique:true);` If you need to identify the parent by something other than _id, use that instead. – Joe Mar 06 '20 at 18:32
  • @Joe unfortunately not working =/ -- i think that would work if it was a `has many` relationship. It might be thrown off because of the `embeds many` relationship – alilland Mar 06 '20 at 18:40
  • that it might be. – Joe Mar 06 '20 at 18:44
  • I'd personally bypass mongoose and create the index in the mongo shell, but that has its own set of issues. – Joe Mar 06 '20 at 18:45

0 Answers0