With a Mongoose schema, Is it possible to define the type of an objects property/keys that are unknown? With a Mongoose schema, Is it possible to define the type of an objects property/keys that are unknown? mongoose mongoose

With a Mongoose schema, Is it possible to define the type of an objects property/keys that are unknown?


There is no option for "wild card" schema path validation as far as I know.What you can do is define a strict: false schema and define a pre save and update functions.

The schema would look like this:

var TestSchema  = new mongoose.Schema(    {    },    {        strict: false    });

it means that there are no defined fields and you can enter any field you want. Now you want to validate the document before saving with a pre save function:

TestSchema.pre('save', function (next) {    var doc = this.toObject();    for (var prop in doc) {        if ('string' !== typeof doc[prop]) {            next(new Error('validation error'));        }    }    next();});

You would want to do same on pre update function. you can read more about mongoose Middleware here:

http://mongoosejs.com/docs/middleware.html