How to use mongoose model schema with dynamic keys?

China☆狼群 提交于 2019-11-28 05:00:16

问题


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.


回答1:


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.




回答2:


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.




回答3:


You can do like this:

posts: { type: Object }

And inside posts key, you can implement any key-value pair you would like to



来源:https://stackoverflow.com/questions/36228599/how-to-use-mongoose-model-schema-with-dynamic-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!