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: {
// ...
}
})