How to use mongoose model schema with dynamic keys?

Ahmed Commando picture Ahmed Commando · Mar 25, 2016 · Viewed 11.1k times · Source

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.

Answer

Rash picture Rash · Mar 26, 2019

If I understand correctly, you want to add a new column to your schema whose key is generated dynamically. E.g. maybe a collection of posts per user, where the heading of post is the key. If a user creates a new post, it gets added to his collection with the key as his post's heading.

When you originally did

let schema = new Schema({ id: String, ... , key: String })

mongoose took key literally, just like it took id literally.

The reason why you cannot add keys dynamically to the root of the schema is because then mongoose can't guarantee any structure. You might as well do strict: false, as others have suggested, to make the entire schema free-form.

However, if you don't want to make the entire schema free-form, but only a certain portion of it, you can also modify your schema to use mixed

let schema = new Schema({ id: String, ... , posts: Schema.Types.Mixed })

Now you can save all your dynamically generated keys under posts which is free-form.

You can also do above with map:

let schema = new Schema({ id: String, ... , posts: {type: Map, of: String} })

This will allow you to create any key-value pair inside the posts structure.