基于自定义Schema的Mongoose验证:动态键字段校验求助
schema1.translation.en with schema2 Rules in Mongoose I’ve dealt with this exact Mongoose validation limitation before—since loose Object types don’t support dynamic key schema associations, we need workarounds to reuse your schema2 rules for the translation.en field. Here are two reliable approaches:
1. Custom Validator That Reuses schema2’s Validation Logic
This method lets you keep translation as a plain Object while manually validating the en field against schema2’s rules. We’ll create a temporary model instance from schema2 to leverage its built-in validation:
const mongoose = require('mongoose'); const { Schema } = mongoose; // Your original schema2 const schema2 = new Schema({ content: String }); // Schema1 with custom validation for translation.en const schema1 = new Schema({ code: String, translation: { type: Object, validate: { validator: function(translationObj) { // Optional: enforce that translation.en exists (adjust based on your needs) if (!translationObj?.en) { return false; } // Create a temporary document using schema2 to validate the en value const tempValidationDoc = new mongoose.Model('TempValidation', schema2)({ content: translationObj.en }); // Check for validation errors const validationErrors = tempValidationDoc.validateSync(); return !validationErrors; }, message: (props) => `translation.en failed schema2 validation: ${props.value}` } } });
Notes:
- If your
schema2uses async validators (like database checks), switch to anasyncvalidator function and return a promise instead of usingvalidateSync. - Adjust the "required" check for
translation.enbased on whether that field is mandatory in your use case.
2. Define translation as a Nested Schema (Recommended for Fixed Language Keys)
If your translation object has a predictable set of keys (like en, fr, es), ditch the plain Object type and define translation as a nested schema. This lets you directly attach schema2’s rules to the en field:
const mongoose = require('mongoose'); const { Schema } = mongoose; // Your original schema2 const schema2 = new Schema({ content: String }); // Define a nested schema for translation, reusing schema2's structure const translationSchema = new Schema({ en: schema2.obj, // Reuse the exact field rules from schema2 // Add other language keys here if needed (e.g., fr: schema2.obj) }); // Final schema1 with structured translation field const schema1 = new Schema({ code: String, translation: translationSchema });
Why This Works:
Mongoose fully supports nested schemas, so each language key (like en) inherits all validation rules from schema2 without any hacks. This is cleaner and more maintainable if your translation keys are fixed.
Why Your Initial Approach Didn’t Work
Mongoose’s plain Object type is designed for unstructured data, so it doesn’t support attaching schemas to dynamic keys. The above methods either explicitly validate the target key or structure your data to fit Mongoose’s schema validation system.
内容的提问来源于stack exchange,提问作者Nomanoclass

