Get parent schema property for validation using Mongoose and MongoDB

Let's say that I have a nested diagram (invitation) in another diagram (element), and when I try to save the invitation object, I want to check whether the parent property is β€œincluded” from the element scheme in true or false before allowing the person to save the invitation object in array of invitations. Obviously this.enabled does not work as it tries to remove it from a prompt that does not exist. How to get the "enabled" property in the parent schema for validation?

Any thoughts? Thanks for any help!

var validateType = function(v) { if (v === 'whateverCheck') { return this.enabled || false; <== this doesn't work } else { return true; } }; var invitationSchema = new Schema({ name: { type: String }, type: { type: String, validate: [validateType, 'error message.'] } }); var itemSchema = new Schema({ title: { type: String }, description: { type: String }, enabled: {type: Boolean}, <== trying to access this here invitations: { type: [ invitationSchema ] }, }); var ItemModel = mongoose.model('Item', itemSchema, 'items'); var InvitationModel = mongoose.model('Invitation', invitationSchema); 
+5
source share
1 answer

An embedded document parent is accessible from an instance of the embedded document model by calling instance.parent(); . This way you can do this from any Mongoose middleware, for example with a validator or hook.

In your case, you can do:

 var validateType = function(v) { if (v === 'whateverCheck') { return this.parent().enabled || false; // <== this does work } else { return true; } }; 
+1
source

All Articles