I have a simple Mongoose schema that looks like this:
const fruitSchema = new mongoose.Schema({
name: {
type: String
required: true
},
type: {
type: String,
required: true
}
})
schema.index({ name: 1, type: 1 }, { unique: true })
const Fruit = mongoose.model('Fruit', fruitSchema)
Under normal circumstances, the table is unique on (name, type)
so the user is able to store multiple types for each fruit. However, I want to allow the user to only store one type
if the name
of the Fruit
is apple
.
So basically, I want make the following check before a save is made:
if (newFruit.name === 'apple') {
if (Fruit.find({ name: 'apple' }).count >= 1) throw new Error()
}
One way of enforcing this is to execute the code above in a pre-save hook. But, I was just wondering if there would be an in-built way to specify this within the Mongoose schema itself?
Thanks for the help!
SOLUTION: In addition to the solution kindly provided by @SuleymanSah below, I thought I'd post what I finally ended up using.
const fruitSchema = new mongoose.Schema({
fruit: {
type: String
required: true,
async validate(name) {
if (name === 'apple') {
let fruit
try {
fruit = await Fruit.findOne({ name })
} catch (e) {
console.error('[Fruit Model] An error occurred during validation.')
console.error(e)
throw e // rethrow error if findOne call fails since fruit will be null and this validation will pass with the next statement
}
if (fruit) throw new Error(`A fruit for ${name} already exists.`)
}
},
type: {
type: String,
required: true
}
})
schema.index({ fruit: 1, type: 1 }, { unique: true })
const Fruit = mongoose.model('Fruit', fruitSchema)