mongoose#SchemaDefinition TypeScript Examples

The following examples show how to use mongoose#SchemaDefinition. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: generateModel.ts    From davinci with MIT License 5 votes vote down vote up
createMongooseSchema = (classSchema: ClassType, definition: SchemaDefinition, options: SchemaOptions) => {
	const allMethods = Reflector.getMetadata('davinci:mongoose:methods', classSchema.prototype.constructor) || [];

	// get methods
	const methods = allMethods
		.filter(({ isPrototype }) => isPrototype)
		.filter(({ name }) => !EXCLUDED_INSTANCE_METHODS.includes(name))
		.reduce((acc, { name, handler }) => ({ ...acc, [name]: handler }), {});

	// get statics
	const statics = allMethods
		.filter(({ isStatic }) => isStatic)
		.filter(({ name }) => !EXCLUDED_STATIC_METHODS.includes(name))
		.reduce((acc, { name, handler }) => ({ ...acc, [name]: handler }), {});

	// get indexes
	const indexes = Reflector.getMetadata('davinci:mongoose:indexes', classSchema) || [];

	// get virtual fields that allow population
	const populates = Reflector.getMetadata('davinci:mongoose:populates', classSchema.prototype.constructor) || [];

	// get virtual fields
	const virtuals = Reflector.getMetadata('davinci:mongoose:virtuals', classSchema.prototype.constructor) || [];

	// get schema options
	const decoratorOptions = Reflector.getMetadata('davinci:mongoose:schemaOptions', classSchema.prototype.constructor);

	const schema = new Schema(definition, options ?? decoratorOptions);
	schema.methods = methods;
	schema.statics = statics;
	if (indexes.length > 0) {
		indexes.forEach(({ index, options: o }) => schema.index(index, o));
	}
	virtuals.forEach(({ name, options: opts, handler }) => {
		const virtual = schema.virtual(name, opts);
		if (typeof handler === 'function') {
			virtual.get(handler);
		}
	});
	populates.forEach(({ name, options: o }) => schema.virtual(name, o));

	return schema;
}
Example #2
Source File: buildSchema.ts    From payload with MIT License 4 votes vote down vote up
fieldToSchemaMap = {
  number: (field: NumberField, fields: SchemaDefinition, config: SanitizedConfig, buildSchemaOptions: BuildSchemaOptions): SchemaDefinition => {
    const baseSchema = { ...formatBaseSchema(field, buildSchemaOptions), type: Number };

    return {
      ...fields,
      [field.name]: localizeSchema(field, baseSchema, config.localization.locales),
    };
  },
  text: (field: TextField, fields: SchemaDefinition, config: SanitizedConfig, buildSchemaOptions: BuildSchemaOptions): SchemaDefinition => {
    const baseSchema = { ...formatBaseSchema(field, buildSchemaOptions), type: String };

    return {
      ...fields,
      [field.name]: localizeSchema(field, baseSchema, config.localization.locales),
    };
  },
  email: (field: EmailField, fields: SchemaDefinition, config: SanitizedConfig, buildSchemaOptions: BuildSchemaOptions): SchemaDefinition => {
    const baseSchema = { ...formatBaseSchema(field, buildSchemaOptions), type: String };

    return {
      ...fields,
      [field.name]: localizeSchema(field, baseSchema, config.localization.locales),
    };
  },
  textarea: (field: TextareaField, fields: SchemaDefinition, config: SanitizedConfig, buildSchemaOptions: BuildSchemaOptions): SchemaDefinition => {
    const baseSchema = { ...formatBaseSchema(field, buildSchemaOptions), type: String };

    return {
      ...fields,
      [field.name]: localizeSchema(field, baseSchema, config.localization.locales),
    };
  },
  richText: (field: RichTextField, fields: SchemaDefinition, config: SanitizedConfig, buildSchemaOptions: BuildSchemaOptions): SchemaDefinition => {
    const baseSchema = { ...formatBaseSchema(field, buildSchemaOptions), type: Schema.Types.Mixed };

    return {
      ...fields,
      [field.name]: localizeSchema(field, baseSchema, config.localization.locales),
    };
  },
  code: (field: CodeField, fields: SchemaDefinition, config: SanitizedConfig, buildSchemaOptions: BuildSchemaOptions): SchemaDefinition => {
    const baseSchema = { ...formatBaseSchema(field, buildSchemaOptions), type: String };

    return {
      ...fields,
      [field.name]: localizeSchema(field, baseSchema, config.localization.locales),
    };
  },
  point: (field: PointField, fields: SchemaDefinition, config: SanitizedConfig): SchemaDefinition => {
    const baseSchema = {
      type: {
        type: String,
        enum: ['Point'],
      },
      coordinates: {
        type: [Number],
        sparse: field.unique && field.localized,
        unique: field.unique || false,
        required: (field.required && !field.localized && !field?.admin?.condition && !field?.access?.create) || false,
        default: field.defaultValue || undefined,
      },
    };

    return {
      ...fields,
      [field.name]: localizeSchema(field, baseSchema, config.localization.locales),
    };
  },
  radio: (field: RadioField, fields: SchemaDefinition, config: SanitizedConfig, buildSchemaOptions: BuildSchemaOptions): SchemaDefinition => {
    const baseSchema = {
      ...formatBaseSchema(field, buildSchemaOptions),
      type: String,
      enum: field.options.map((option) => {
        if (typeof option === 'object') return option.value;
        return option;
      }),
    };

    return {
      ...fields,
      [field.name]: localizeSchema(field, baseSchema, config.localization.locales),
    };
  },
  checkbox: (field: CheckboxField, fields: SchemaDefinition, config: SanitizedConfig, buildSchemaOptions: BuildSchemaOptions): SchemaDefinition => {
    const baseSchema = { ...formatBaseSchema(field, buildSchemaOptions), type: Boolean };

    return {
      ...fields,
      [field.name]: localizeSchema(field, baseSchema, config.localization.locales),
    };
  },
  date: (field: DateField, fields: SchemaDefinition, config: SanitizedConfig, buildSchemaOptions: BuildSchemaOptions): SchemaDefinition => {
    const baseSchema = { ...formatBaseSchema(field, buildSchemaOptions), type: Date };

    return {
      ...fields,
      [field.name]: localizeSchema(field, baseSchema, config.localization.locales),
    };
  },
  upload: (field: UploadField, fields: SchemaDefinition, config: SanitizedConfig, buildSchemaOptions: BuildSchemaOptions): SchemaDefinition => {
    const baseSchema = {
      ...formatBaseSchema(field, buildSchemaOptions),
      type: Schema.Types.Mixed,
      ref: field.relationTo,
    };

    return {
      ...fields,
      [field.name]: localizeSchema(field, baseSchema, config.localization.locales),
    };
  },
  relationship: (field: RelationshipField, fields: SchemaDefinition, config: SanitizedConfig, buildSchemaOptions: BuildSchemaOptions) => {
    const hasManyRelations = Array.isArray(field.relationTo);
    let schemaToReturn: { [key: string]: any } = {};

    if (field.localized) {
      schemaToReturn = {
        type: config.localization.locales.reduce((locales, locale) => {
          let localeSchema: { [key: string]: any } = {};

          if (hasManyRelations) {
            localeSchema._id = false;
            localeSchema.value = {
              type: Schema.Types.Mixed,
              refPath: `${field.name}.${locale}.relationTo`,
            };
            localeSchema.relationTo = { type: String, enum: field.relationTo };
          } else {
            localeSchema = {
              ...formatBaseSchema(field, buildSchemaOptions),
              type: Schema.Types.Mixed,
              ref: field.relationTo,
            };
          }

          return {
            ...locales,
            [locale]: field.hasMany ? [localeSchema] : localeSchema,
          };
        }, {}),
        localized: true,
      };
    } else if (hasManyRelations) {
      schemaToReturn._id = false;
      schemaToReturn.value = {
        type: Schema.Types.Mixed,
        refPath: `${field.name}.relationTo`,
      };
      schemaToReturn.relationTo = { type: String, enum: field.relationTo };

      if (field.hasMany) schemaToReturn = [schemaToReturn];
    } else {
      schemaToReturn = {
        ...formatBaseSchema(field, buildSchemaOptions),
        type: Schema.Types.Mixed,
        ref: field.relationTo,
      };

      if (field.hasMany) schemaToReturn = [schemaToReturn];
    }

    return {
      ...fields,
      [field.name]: schemaToReturn,
    };
  },
  row: (field: RowField, fields: SchemaDefinition, config: SanitizedConfig, buildSchemaOptions: BuildSchemaOptions): SchemaDefinition => {
    const newFields = { ...fields };

    field.fields.forEach((rowField: Field) => {
      const fieldSchemaMap: FieldSchemaGenerator = fieldToSchemaMap[rowField.type];

      if (fieldSchemaMap && fieldAffectsData(rowField)) {
        const fieldSchema = fieldSchemaMap(rowField, fields, config, buildSchemaOptions);
        newFields[rowField.name] = fieldSchema[rowField.name];
      }
    });

    return newFields;
  },
  array: (field: ArrayField, fields: SchemaDefinition, config: SanitizedConfig, buildSchemaOptions: BuildSchemaOptions) => {
    const baseSchema = {
      ...formatBaseSchema(field, buildSchemaOptions),
      type: [buildSchema(config, field.fields, {
        options: { _id: false, id: false },
        allowIDField: true,
        disableUnique: buildSchemaOptions.disableUnique,
      })],
    };

    return {
      ...fields,
      [field.name]: localizeSchema(field, baseSchema, config.localization.locales),
    };
  },
  group: (field: GroupField, fields: SchemaDefinition, config: SanitizedConfig, buildSchemaOptions: BuildSchemaOptions): SchemaDefinition => {
    let { required } = field;
    if (field?.admin?.condition || field?.localized || field?.access?.create) required = false;

    const formattedBaseSchema = formatBaseSchema(field, buildSchemaOptions);

    const baseSchema = {
      ...formattedBaseSchema,
      required: required && field.fields.some((subField) => (!fieldIsPresentationalOnly(subField) && subField.required && !subField.localized && !subField?.admin?.condition && !subField?.access?.create)),
      type: buildSchema(config, field.fields, {
        options: {
          _id: false,
          id: false,
        },
        disableUnique: buildSchemaOptions.disableUnique,
      }),
    };

    return {
      ...fields,
      [field.name]: localizeSchema(field, baseSchema, config.localization.locales),
    };
  },
  select: (field: SelectField, fields: SchemaDefinition, config: SanitizedConfig, buildSchemaOptions: BuildSchemaOptions): SchemaDefinition => {
    const baseSchema = {
      ...formatBaseSchema(field, buildSchemaOptions),
      type: String,
      enum: field.options.map((option) => {
        if (typeof option === 'object') return option.value;
        return option;
      }),
    };
    const schemaToReturn = localizeSchema(field, baseSchema, config.localization.locales);

    return {
      ...fields,
      [field.name]: field.hasMany ? [schemaToReturn] : schemaToReturn,
    };
  },
  blocks: (field: BlockField, fields: SchemaDefinition, config: SanitizedConfig): SchemaDefinition => {
    const baseSchema = [new Schema({ }, { _id: false, discriminatorKey: 'blockType' })];
    let schemaToReturn;

    if (field.localized) {
      schemaToReturn = config.localization.locales.reduce((localeSchema, locale) => ({
        ...localeSchema,
        [locale]: baseSchema,
      }), {});
    } else {
      schemaToReturn = baseSchema;
    }

    return {
      ...fields,
      [field.name]: schemaToReturn,
    };
  },
}