Require One of Several Columns on Mongoose.js Require One of Several Columns on Mongoose.js mongoose mongoose

Require One of Several Columns on Mongoose.js


I'd try using a global pre-validation hook:

const providers = ['google', 'twitter', 'facebook', 'local'];userSchema.pre('validate', function(next) { let hasProvider = false; // not sure if this is needed, but sometimes, the scoping is messed up const that = this; // you should add more validations, e.g. for fields, too hasProvider = providers.some(provider => that.hasOwnProperty(provider)); return (hasProvider) ? next() : next(new Error('No Provider provided'));});

Note: This only works, if the pre-validation hook is actually being called. If you only use .save() you should be fine according to the docs.:

The save() function triggers validate() hooks, because mongoose has a built-in pre('save') hook that calls validate(). This means that all pre('validate') and post('validate') hooks get called before any pre('save') hooks.

If you use a function that circuments the validation, this might lead to problems. Check https://mongoosejs.com/docs/validation.html for more info!