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_nam
You can do like this:
posts: { type: Object }
And inside posts key, you can implement any key-value pair you would like to
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.
const options = {};
options[key] = String;
schema.add(options);
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.