Search code examples
node.jsmongoose-schema

How to use mongoose model schema with dynamic keys?


i'm using mongoose with nodejs, and i need to create a dynamic schema model, this is my code:

schema.add({key : String});

key = "user_name", but in my db i found that the model take it as key

{ key : "Michele" } and not { user_name: "Michele"}

What can i do? thank you.


Solution

  • The same issue schema with variable key is talked in mongoose,

    Nope not currently possible. Closest alternative is to use strict: false or the mixed schema type.

    Update

    After Mongoose 5.1.0, we can use the terms 'map', maps are how you create a nested document with arbitrary keys

    const userSchema = new Schema({
      // `socialMediaHandles` is a map whose values are strings. A map's
      // keys are always strings. You specify the type of values using `of`.
      socialMediaHandles: {
        type: Map,
        of: String
      }
    });
    
    const User = mongoose.model('User', userSchema);
    // Map { 'github' => 'vkarpov15', 'twitter' => '@code_barbarian' }
    console.log(new User({
      socialMediaHandles: {
        github: 'vkarpov15',
        twitter: '@code_barbarian'
      }
    }).socialMediaHandles);