Mongoose Object Type

I define the mongoose pattern and definition as follows:

   inventoryDetails: {
        type: Object,
        required: true

    },
    isActive:{
        type:Boolean,
        default:false
    }

I tried the type "Object", and I see that my data is successfully saved. When I changed the type to an array, saving is not performed.

Data examples

{
    "inventoryDetails" : { 
        "config" : { 
            "count" : { 
                "static" : { "value" : "123" }, 
                "dataSource" : "STATIC" 
            }, 
            "title" : { 
                "static" : { "value" : "tik" }, 
                "dataSource" : "STATIC" 
            } 
        }, 
        "type" : "s-card-with-title-count" 
    } 
}

The type "Object" is not one of the types that allows the use of mongoose. But how is it supported?

+4
source share
1 answer

You have two options for getting Objectin db:

1. Define it 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 data structure of an object.

If you want to create a flexible data structure for an object, see the following.

2. Schema.Types.Mixed

, doc:

let YourSchema = new Schema({
  inventoryDetails: Schema.Types.Mixed
})

let yourSchema = new YourSchema;

yourSchema.inventoryDetails = { any: { thing: 'you want' } }

yourSchema.save()
+10

Source: https://habr.com/ru/post/1668708/


All Articles