Create Model of Schema Mongoose (Node.js) for simplify the code

Viewed 71

I checked the previous examples but couldn't find any ideas. Programming means don't repeat yourself, and I want create a model , but I didn't understand how to do it, I would like to apply it to the example below. thanks

const mongoose = require('mongoose');  
const fasiSchema = mongoose.Schema({
    controlloMateriale : {
        tempoaSchedaInOre: {  type: Date, required: false  },
        tempoTotaleInOre: {  type: Date, required: false }       
    },
    equipaggiamento : {
        tempoaSchedaInOre: {  type: Date, required: false  },
        tempoTotaleInOre: {  type: Date, required: false }
    },
});

mongoose.model('fasi',fasiSchema);
2 Answers

In cases such as that there is no alternative. You simply have to repeat yourself. You could create a system with templates and such but it probably wouldn't help much

It's pretty straight forward. Just create a const with the common schema value and use that where value is repeated

const mongoose = require('mongoose');  

const DateSchema = {  type: Date, required: false };
const CustomSchema = {
            tempoaSchedaInOre: DateSchema,
            tempoTotaleInOre: DateSchema  };

const fasiSchema = new mongoose.Schema({
        controlloMateriale : CustomSchema,
        equipaggiamento : CustomSchema,
    });

mongoose.model('fasi',fasiSchema);
Related