Monday 20 May 2019

Mongoose: how to use custom options in schemas?

I'm trying to create a Mongoose model, Event, where a user would be able to create a document in the database with just an event name, which would be saved as a draft by default (published = false). I'd like the model to be able to validate whether an event can be set as published, and my thought was to define something like this in the model:​const EventSchema = new mongoose.Schema({name: {type: String,required: true,maxLength: 100,trim: true,},description: {type: String,required: false,requiredForPublish: true,maxLength: 5000,trim: true,},published: {type: Boolean,default: false,required: true,},...});​As far as I understand there's nothing stopping me from setting these kinds of custom properties on my schema fields, but how would I actually then use them? Say I wanted to have a pre-save hook that checks if we are trying to set published to true and if so, check that all the fields with requiredForPublish are set on the document, and throw an error if that's not the case.

Submitted May 20, 2019 at 03:47PM by sourtargets

No comments:

Post a Comment