Home > Enterprise >  Create mongodb document with uuid named Object keys
Create mongodb document with uuid named Object keys

Time:04-06

I want to create a document like shown below in mongoose. There is a pageElements Object with uuid Object keys inside.

{
    "pageElements": {
        "fc6b151-cd5-3c1-0e00-241b4411d4eb": {
            "containers": {
                "de325a-acb2-e0a1-e521-20b3e81e33f": {
                    "components": [{
                        ...
                    }],
                }
            },
        },
        "075f7c-5aff-c850-a731-a8dff1bea5f8": {
            "containers": {
                ...
            }
        }
    },
}

I tried to create the Schema like this:


const componentSchema = new mongoose.Schema(
  {
    ...
  },
);

const containersSchema = new mongoose.Schema(
  {
    components: [{ type: componentSchema, required: true }],
  },
);

const pageElementsSchema = new mongoose.Schema(
  {
    containers: { type: containersSchema, required: true },
  },
);

const pageSchema = new mongoose.Schema(
  {
    pageElements: {
      type: pageElementsSchema,
    },
  },
);

But the new created document only contains an empty pageElements Object.

CodePudding user response:

Use Map as

const componentSchema = new mongoose.Schema(
  {
    ...
  },
);

const containersMapSchema = new mongoose.Schema(
  {
    components: [{ type: componentSchema, required: true }],
  },
);

const pageElementsMapSchema = new mongoose.Schema({
  containers: { 
    type: Map,
    of: containersMapSchema
  }
})

const pageSchema = new mongoose.Schema(
  {
    pageElements: {
      type: Map,
      of: pageElementsMapSchema
    },
  },
);
  • Related