Как запустить схему мангуста при создании экземпляра вместо save()?

#javascript #node.js #mongodb #mongoose

Вопрос:

Я должен построить схему с мангустом. Это первая схема.

     const mongoose = require('mongoose');
    const {
  formatToCamelCase,
  formatToCapitalizeEach
} = require('../src/util/formatter');

const formAttributeElementSchema = new mongoose.Schema({
  elementTitle: {
    type: String,
    required: [true, 'Please provide element title in formAttributeSchema.'],
    set: elementTitle => formatToCapitalizeEach(elementTitle),
  },

  datatype: {
    type: String,
    required: [true, 'Please provide data type for form attribute.'],
    lowercase: true,
    enum: {
      values: ['string', 'number'],
      message: 'We still not support {VALUE} data type in form attribute'
    },
    default: 'string',
  },

  attributeName: {
    type: String,
    required: [true, 'Please provide attribute name in form atribute schema.'],
    set: attributeName => formatToCamelCase(attributeName),
  },

  isRequired: {
    type: Boolean,
    required: true,
    default: true,
  },

  HTMLInputType: {
    type: String,
    required: [true, 'Please determine HTML input type for this form attribute.'],
    enum: {
      values: ['text', 'radio', 'checkbox'],
      message: '{VALUE} is not supported yet. Please use supported type.',
    },
  },

  maxLength: {
    type: Number,
    required: false,
    validate: {
      validator: (maxLength) => {
        if (maxLength <= 0) return false;
      },
      message: 'Max length value can not have 0 or negative value.',
    }
  },

  minLength: {
    type: Number,
    required: false,
    validate: {
      validator: (minLength) => {
        if (minLength < 0) return false;
      },
      message: 'Min length can not have negative value.'
    }
  }
}, { _id: false });

const FormAttributeElement = mongoose.model('FormAttributeElement', formAttributeElementSchema);

module.exports = { FormAttributeElement };
 

и вторая схема такова:

 const mongoose = require('mongoose');
const { formatToCapitalizeEach } = require('../src/util/formatter');
const { emailValidator } = require('../src/util/validator');
const { FormAttributeElement } = require('./formAttributeElement');

const dynamicFormDetails = new mongoose.Schema({
  formTitle: {
    type: String,
    required: [true, 'Please provide form title.'],
    set: formTitle => formatToCapitalizeEach(formTitle),
  },

  issuer: {
    type: String,
    required: [true, 'Please provide issuer email on form detail.'],
    lowercase: true,
    validate: {
      validator: (issuer) => emailValidator(issuer),
      message: 'Please makse sure use correct email format in issuer field on form detail attribute.',
    },
  },

  startAt: {
    type: Date,
    required: [true, 'please provide date on startAt attribute.'],
  },

  closedAt: {
    type: Date,
    required: [true, 'Please provide date on closedAt attribute']
  },

  formShape: {
    type: Array,
    required: [true, 'Please provide form shape in form details.'],
    validate: {
      validator: (formShape) => {
        for (let i = 0; i < formShape.length; i  = 1) {
          if (!formShape[i] instanceof FormAttributeElement) return false;
        }
      },
      message: 'Form body only can be instance of FormAttributeElement',
    },
  },
});

const DynamicFormDetail = mongoose.model('DynamicFormDetail', dynamicFormDetails);

module.exports = { DynamicFormDetail };
 

теперь я хочу протестировать свою схему, особенно ее проверку с помощью этого кода:

 const { mongodbAtlasConnection } = require('../db/mongodb-connection');
const { DynamicFormDetail } = require('./dynamicForm');
const { FormAttributeElement } = require('./formAttributeElement');


const main = async () => {
  let formElements = [];
  let element;
  const body = [
    {
      elementTitle: 'test aku hanya ngetes',
      datatype: 'anjir harusnya gabisa sih',
      isRequired: true,
      HTMLInputType: 'blah',
    }
  ]

  body.forEach((data) => {
    element = new FormAttributeElement({
      elementTitle: data.elementTitle,
      datatype: data.datatype,
      attributeName: data.elementTitle,
      isRequired: data.isRequired,
      HTMLInputType: data.HTMLInputType,
    });

    formElements.push(element);
  });

  const formDetails = new DynamicFormDetail({
    formTitle: 'test 123 form title',
    issuer: 'lucky@gmail.com',
    startAt: '2021-10-6',
    closedAt: '2021-10-7',
    formShape: formElements,
  });

  try {
    await mongodbAtlasConnection();
    const result = await formDetails.save();
    console.log(result);
  } catch (e) {
    console.log(e)
  }
}

main();
 

Да, в модели DynamicFormDetail проверка работает просто отлично. Если мне не был предоставлен обязательный атрибут, он выдает ошибку. Но проблема в том, что при создании экземпляра FormAttributeElement (внутри цикла forEach) я могу вставить что угодно, даже если это противоречит ограничению, которое я определил в схеме. Как запустить эту проверку, если я не хочу использовать функцию .save() в этой модели?

Комментарии:

1. извините, что это была опечатка. не к схеме, а к двум схемам

2. Модель имеет validate метод см. документы mongoosejs.com/docs/api/model.html#model_Model.validate

3. @Molda Почему вы не добавили в качестве ответа?