What to do with ENUM values in Mongoose? What to do with ENUM values in Mongoose? mongoose mongoose

What to do with ENUM values in Mongoose?


You can use admin panel to add more country to the country collection. As you are saying that COUNTRIES array can grow, you can use another collection to add more countries on demand from admin panel.

And when you are going to add/save a new record into the survey you can trigger a pre-save hook to mongo for validation.

suppose we have another schema for countries like this.

{ countries: [String]}

Here is a sample code for the scenario.

const mongoose = require("mongoose");const GENDERS = ["M", "F"];const surveySchema = {    subject: { type: String, required: true },    country: { type: String},    target: {        gender: { type: String, enum: GENDERS }    }};var Survey = new mongoose.Schema(surveySchema);Survey.pre('save',function(next){  var me = this;  CountryModel.find({},(err,docs)=>{    (docs.countries.indexOf(me.country) >=0) ? next() : next(new Error('validation failed'));  });});

This way you can handle dynamic country add without changing the country array and redeploying your whole server.

USING CUSTOM VALIDATOR

const mongoose = require("mongoose");const GENDERS = ["M", "F"];const surveySchema = {        subject: {            type: String,            required: true        },        country: {            type: String,            validate: {                isAsync: true,                validator: function(arg, cb) {                    CountryModel.find({}, (err, docs) => {                                if (err) {                                    cb(err);                                } else {                                    cb(docs.countries.indexOf(arg) >= 0);                                }                            }                        },                        message: '{VALUE} is not a valid country'                }            },            target: {                gender: { type: String, enum: GENDERS }            }        };

you will get an error while saving the survey data in the callback ..

ServeyModel.save((err,doc)=>{if(err){console.log(err.errors.country.message);//Error handle}else {//TODO}});


Just wanted to add one thing, @Shawon's answer is great. Do know that there are two ways to make a validator async. One is shown above where if you specify the isAsync flag and then Mongoose will pass that callback into your validator function to be called at the end of your validation, but you should only use that flag if you're not returning a promise. If you return a promise from your custom validator, Mongoose will know it is async and the isAsync flag is no longer required.

The Mongoose async custom validator doc is found here which shows these both examples really well, great docs. http://mongoosejs.com/docs/validation.html#async-custom-validators