Object type in mongoose

前端 未结 1 1038
挽巷
挽巷 2021-02-06 22:26

I am defining a mongoose schema and definition is as follows:

   inventoryDetails: {
        type: Object,
        required: true

    },
    isActive:{
                 


        
相关标签:
1条回答
  • 2021-02-06 22:42

    You have two options to get your Object in the db:

    1. Define it by yourself

    let YourSchema = new Schema({
      inventoryDetails: {
        config: {
          count: {
            static: {
              value: {
                type: Number,
                default: 0
              },
              dataSource: {
                type: String
              }
            }
          }
        },
        myType: {
          type: String
        }
      },
      title: {
        static: {
          value: {
            type: Number,
            default: 0
          },
          dataSource: {
            type: String
          }
        }
      }
    })
    

    Take a look at my real code:

    let UserSchema = new Schema({
      //...
      statuses: {
        online: {
          type: Boolean,
          default: true
        },
        verified: {
          type: Boolean,
          default: false
        },
        banned: {
          type: Boolean,
          default: false
        }
      },
      //...
    })
    

    This option gives you the ability to define the object's data structure.

    If you want a flexible object data structure, see the next one.

    2. Use the default Schema.Types.Mixed type

    Example taken from the doc:

    let YourSchema = new Schema({
      inventoryDetails: Schema.Types.Mixed
    })
    
    let yourSchema = new YourSchema;
    
    yourSchema.inventoryDetails = { any: { thing: 'you want' } }
    
    yourSchema.save()
    
    0 讨论(0)
提交回复
热议问题