Estoy tratando de crear un nuevo documento en la colección de Form . Este documento hace referencia a muchos documentos FormSection . Aquí están los esquemas:
const FormSchema = new Schema({ title: { type: String, required: true, unique: true }, description: { type: String, required: true, unique: true }, sections: [{ type: FormSectionDetails }], createdDate: { type: String, required: false, unique: true }, lastEdited: { type: String, required: false, unique: true } }); const FormSectionDetails = new Schema({ section: { type: Schema.Types.ObjectId, ref: 'FormSection', required: true }, position: { type: Number, required: true } }); const FormSectionSchema = new Schema({ name: { type: String, required: true, unique: true }, display: { type: String, required: true, }, category: { type: String, required: true }, ... }); let FormSection; try { FormSection = mongoose.connection.model('FormSection'); } catch (e) { FormSection = mongoose.model('FormSection', FormSectionSchema); } Sin embargo, cuando intento agregar un nuevo documento a la colección de Forms , aparece un error:
Documento que se inserta:
formData = { "title": "Returning Members", "description": "Returning Members", "sections": [{ "section": "6292c0fbd4837faca1d85d4d", "position": 1 }, { "section": "6292c0fbd4837faca1d85d4e", "position": 2 }, ... }Código que se está ejecutando:
formdata.sections.map(s => { return { ...s, section: ObjectId(s.section), }} ); return await FormSection.create(formdata);Mensaje de error:
ValidationError: category: Path `category` is required., display: Path `display` is required.```` Seems like it is trying to create a new FormSection document. I don't want it to create a new FormSection document. I just want it to reference existing FormSection documents using the Object IDs I specified.El problema parece estar relacionado con la forma en que declara el campo de sección en el FormSchema. Prueba esto:
const FormSchema = new Schema({ title: { type: String, required: true, unique: true }, description: { type: String, required: true, unique: true }, sections: [{ type: ObjectId, ref: 'FormSectionDetails', required: true, }], createdDate: { type: String, required: false, unique: true }, lastEdited: { type: String, required: false, unique: true } });Esto solo almacenaría los _ids de los FormSectionDetails existentes
Resulta que estaba insertando el documento en la colección incorrecta. En lugar del fragmento de código:
return await FormSection.create(formdata);En realidad debería ser:
return await Form.create(formdata);El mensaje de error debería haber sido una pista más obvia para mí sobre cuál era el problema.