Question

I am trying to build a MEAN project, so I need to validate some of my model's dynamic key...

I want to create a Schema like this

var exampleSchema = new Schema({
    x: {
        type: String,
        default: '',
        required: true,
        trim: true
    },
    y: {}
});

as you see I have mixed type object, but actually it is a Language Map and it should be something like this,

{
   "en-US": "answered"
}

can I validate my key with mongoose? (I think it has no function like that)

if no, how and where can I validate it (in model or controller)?

Was it helpful?

Solution

You may want to look into this: http://mongoosejs.com/docs/middleware.html

Specifically pre-save events. Mongoose gives you control over this and you can perform validation, mapping as needed before the actual model gets saved.

Also works nice for pre-init event if you need defaults such as "current date" for an audit trail such as "createdOn: date".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top