How to use mongoose model schema with dynamic keys?

后端 未结 4 1161
轮回少年
轮回少年 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:03

    You can do like this:

    posts: { type: Object }
    

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

    0 讨论(0)
  • 2021-01-13 18:04

    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.

    0 讨论(0)
  • 2021-01-13 18:07
    const options = {};
    options[key] = String;
    
    schema.add(options);
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题