Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 950
Ahmed Commando Avatar asked Dec 06 '22 18:12

Ahmed Commando


1 Answers

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);

like image 63
zangw Avatar answered Dec 25 '22 22:12

zangw