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.
The same issue schema with variable key
is talked in mongoose,
Nope not currently possible. Closest alternative is to use
strict: false
or themixed
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With