Home > database >  How to loop items in mongoose schema
How to loop items in mongoose schema

Time:02-15

I have mongoose Schema , where i have schemas by language. I want to loop them depend my other language model. Now I have them static(en, ru, ge).

const StrategyTranslatedFieldsSchema = mongoose.Schema(
  {
    title: String,
    teaser: String
  },
  { _id : false }
)

const StrategySchema = mongoose.Schema({
    en: StrategyTranslatedFieldsSchema,
    ge: StrategyTranslatedFieldsSchema,
    ru: StrategyTranslatedFieldsSchema,
},
{
    timestamps: true 
});  

my language schema:

const languageSchema = mongoose.Schema({
    en:{
        type: String,
        default: 'en'
    },
    ru:{
        type: String,
        default: 'ru'
    },
    ge:{
        type: String,
        default: 'ge'
    },
}) 

want something like that:

const mongoose = require('mongoose');
const slug = require('mongoose-slug-updater');
const Language = require('../models/Language')

mongoose.plugin(slug); 

const StrategyTranslatedFieldsSchema = mongoose.Schema(
  {
    title: String,
    teaser: String
  },
  { _id : false }
)

const StrategySchema = mongoose.Schema({
  slug: { 
    type: String, 
    slug: "en.title", 
    slugPaddingSize: 2,  
    unique: true 
  },
  status:{
    type: Boolean,
    default: true
  },
    for(let key in Language){
    key: StrategyTranslatedFieldsSchema
  }
},
{
    timestamps: true 
});  

const Strategy = mongoose.model('strategy', StrategySchema);

module.exports = Strategy;

Also interesting is it good practice to save multilingual data, like that example? Thanks

CodePudding user response:

You can do something like this.

 // create object you want to pass StrategySchema 
 const strategySchemaObject = {
     slug: { 
         type: String, 
         slug: "en.title", 
         slugPaddingSize: 2,  
         unique: true 
     },
     status:{
         type: Boolean,
         default: true
    }
  }

  // add each field to your schema object
  Object.keys(Language.schema.obj).forEach((lang) => {
      strategySchemaObject[lang] = StrategyTranslatedFieldsSchema
   })

  // create your schema
  const StrategySchema = mongoose.Schema(strategySchemaObject, {
      timestamps: true
  })
  • Related