Reputation: 845
I have two models setup:
var ShopsSchema = new mongoose.Schema({
name: {
type: String,
required: true
}
});
var ShopsModel = mongoose.model("Shops", ShopsSchema);
var FieldGroupsSchema = new mongoose.Schema({
title: {
type: String,
required: true
},
fields: [{
label: {
type: String,
required: true
},
handle: {
type: String,
required: true
}
}],
shop: {
type: mongoose.Schema.Types.ObjectId,
ref: "Shops"
}
});
var FieldGroupsModel = mongoose.model("FieldGroups", FieldGroupsSchema)
Each FieldGroups instance has a ShopsModel associated with it.
I need to create an index for the FieldGroupsModel fields[i].handle
value, this index needs two rules; it needs to be unique to each FieldGroupsModel instance, so this data would be invalid:
{
title: "Some field group title here",
fields: [
{
label: "Some label 1"
handle: "some-label-1"
},
{
label: "Some label 1"
handle: "some-label-1" // Error: `some-label-1` already exists as a value of `fields[i].handle`.
}
],
shop: {
"$oid": "1"
}
}
The second rule is that the first rule should only be in place for FieldGroupsModel instances which share the same shop
value. So this data would be invalid:
// First bit of data
{
title: "Some field group title here",
fields: [
{
label: "Some label 1"
handle: "some-label-1"
}
],
shop: {
"$oid": "1"
}
}
// Second bit of data
{
title: "Another field group title here",
fields: [
{
label: "Some label 1"
handle: "some-label-1" // Error: `some-label-1` already exists as a value of `fields[i].handle` of a document which shares the same `shop` value.
}
],
shop: {
"$oid": "1"
}
}
However, this would be valid:
// First bit of data
{
title: "Some field group title here",
fields: [
{
label: "Some label 1"
handle: "some-label-1"
}
],
shop: {
"$oid": "1"
}
}
// Second bit of data
{
title: "Another field group title here",
fields: [
{
label: "Some label 1"
handle: "some-label-1" // This is valid because there's no other documents with the same `shop` value with the same `fields[i].handle` value.
}
],
shop: {
"$oid": "2"
}
}
I'm quite new to Mongo and Mongoose so any help here would be greatly appreciated! :)
Upvotes: 3
Views: 11056
Reputation: 626
You call the index
method on your Schema object to do that as shown here. For your case it would be something like:
FieldGroupsSchema.index({"shop": 1, "fields.handle": 1}, {unique: true});
Please read the MongoDB documentation about Compound Indexes for more detail.
Upvotes: 8