How to use mongoose model schema with dynamic keys?

后端 未结 4 1160
轮回少年
轮回少年 2021-01-13 17:51

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

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-13 18:18

    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.

提交回复
热议问题