I have the following schema as exemple:
const categorySchema = new mongoose.Schema({
categoryId: {type: Number},
title: {type: String, default: "standard"},
})
I want that the category with categoryId equal 1, must always be "standard", and if the title is not specified, it will assign the categoryId = 1. Is there any way to do that in Mongoose?
Ok so we have two cases here:
category with categoryId equal 1, must always be "standard"
You could use a pre hook, the code would be like this:
const categorySchema = new mongoose.Schema({
categoryId: {type: Number},
title: {type: String, default: "standard"},
})
categorySchema.pre('save', function (){
if(this.categoryId === 1){
this.title = "standard";
}
})
const categoryModel = mongoose.model('Category', categorySchema);
const category = new categoryModel({title: 'Greaat', categoryId: 1});
await category.save();
if the title is not specified, it will assign the categoryId = 1
With your current code it shouldn't work because you're indicating with default: "standard" that if a title is not specified you have to assign standard as default, so you should leave the default property and manage it in the pre hook to achieve that but that logic seems to me complicated maybe you need to think a little bit better what is the problem, because this kind of solutions are overcomplicated IMHO