How to make sure that a combination of keys is unique in nested documents #10013
-
|
It may be that this is a stupid question and the approach itself is completely wrong, but I would still like to get rid of the question: I have a category that can have subcategories. However, I don't want a category with the same name and the same locale to exist twice. My idea was to make a unique key out of "locale" and "name", but I failed with that. Here is the code: export interface ILocalizedCategory {
locale: LocaleEnum;
name: string;
createdAt: Date;
updatedAt: Date;
}
export interface ICategory extends MongoResult {
localizedFields: ILocalizedCategory[];
children: ICategory[];
createdAt: Date;
updatedAt: Date;
}
const LocalizedCategorySchema: Schema = new Schema({
locale: {
type: String,
required: true,
enum: Object.values(LocaleEnum),
index: true,
},
name: {
type: String,
required: true,
index: true,
},
createdAt: {
type: Date,
required: true,
default: new Date(),
immutable: true,
},
updatedAt: {
type: Date,
required: true,
default: new Date(),
},
});
LocalizedCategorySchema.index({locale: 1, name: 1}, {unique: true});
const CategorySchema: Schema = new Schema({
localizedFields: {
type: [LocalizedCategorySchema],
required: true,
},
createdAt: {
type: Date,
required: true,
default: new Date(),
immutable: true,
},
updatedAt: {
type: Date,
required: true,
default: new Date(),
},
});
CategorySchema.add({
children: {
type: [CategorySchema],
required: true,
default: [],
},
});
export const Category = mongoose.model<ICategory>('Category', CategorySchema);Is this possible at all or should I take a completely different approach and for example create all categories as separate documents and only put the Thanks for your help! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
The approach you specified will make sure there aren't multiple |
Beta Was this translation helpful? Give feedback.
The approach you specified will make sure there aren't multiple
Categorydocuments that have the samelocale, name, but oneCategorydocument can still have duplicatelocale, name. Try mongoose-unique-array, and open an issue on that repo with a repro script if that doesn't work 👍